class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
start = 0
end = len(numbers) - 1
while numbers[start] + numbers[end] != target:
if numbers[start] + numbers[end] > target:
end -= 1
else:
start += 1
return start + 1, end + 1
Sol = Solution()
print Sol.twoSum([2,7,11,15], 9)
0,稍作参考的代码
1,题目要求:
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
2,一开始暴力操作,结果超时,不可行。
然后想到从离target最接近的数值位置开始查找,但是从找到numbers中存在的接近数字,以及再探查,又比较繁琐。
因此利用从两边向中间探查的方法,这样可以有效缩短探查的次数。