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.
Note:
- 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.
Example:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
第一种思路当然是暴力,但是超时
第二种思路就是去两个中间的指针,太大就左指针往左,太小就右指针往右。但是发现如果都在左边,就找不到。所以我打算先找到两个结果的坐标范围内,然后再往外扩。思路就是先取中间位置,判断两倍的值,如果大于结果,就往左移,小于结果就往右移,直到变号(大于变 小于等于,小于变大于等于)。然后以这个位置为中心,如果等于就右指针右移(),小于是右指针右移,大于是左指针左移,(等于的情况是防止[0,0,1,2],0的情况)。
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
length=len(numbers)
res=[]
tempres=0
if(length<=1):
return None
left=right=length//2
if(2*numbers[left]<target):
while(2*numbers[left]<target):
left+=1
right+=1
elif(2*numbers[left]>target):
while(2*numbers[right]>target):
left-=1
right-=1
if(2*numbers[left]==target):
left-=1
#right+=1
while(left>=0 and right<=length-1):
tempres=numbers[left]+numbers[right]
if(tempres==target):
res.append(left+1)
res.append(right+1)
return res
elif(tempres>target):
left-=1
elif(tempres<target):
right+=1
return None
很麻烦。
第三种方法:两个指针从两边开始,大于就右指针左移,小于就左指针右移,不用考虑那么多槽点