167. Two Sum II - Input array is sorted python

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
        

很麻烦。

第三种方法:两个指针从两边开始,大于就右指针左移,小于就左指针右移,不用考虑那么多槽点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值