leetcode算法:Two Sum II - Input array is sorted
Posted 稀里糊涂林老冷
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode算法:Two Sum II - Input array is sorted相关的知识,希望对你有一定的参考价值。
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
1 class Solution(object):
2 def twoSum(self, numbers, target):
3 """
4 :type numbers: List[int]
5 :type target: int
6 :rtype: List[int]
7 """
8 start, end = 0 , len(numbers) - 1
9 while True:
10 if numbers[start] + numbers[end] > target :
11 end -= 1
12 elif numbers[start] + numbers[end] < target :
13 start += 1
14 else :
15 break
16 return (start+1 , end+1 )
17
18
19 if __name__ == ‘__main__‘:
20 s = Solution()
21 res = s.twoSum([2,3,4],6)
22 print(res)
以上是关于leetcode算法:Two Sum II - Input array is sorted的主要内容,如果未能解决你的问题,请参考以下文章
67. Two Sum II - Input array is sorted - LeetCode
leetcode-Two Sum II - Input array is sorted-167