167. Two Sum II - Input array is sorted

16 篇文章 0 订阅
15 篇文章 0 订阅

167. Two Sum II - Input array is sorted

easy

题目

题目
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 开始到倒数第二个遍历,另一个数从 1 开始到最后一个遍历,看两个数之和是否为 target,如果是就输出。代码如下

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        a=[]
        l=len(numbers)
        for i in range(0,l-1):
            for j in range(i+1,l):
                if(numbers[i]+numbers[j]==target):
                    a.append(i+1)
                    a.append(j+1)
        return a

没有 AC,结果是Submission Result: Time Limit Exceeded,经历了双重循环,时间复杂度太高了。

在 discussion 发现了其他解法,值得借鉴:

1.双指针进行二分查找,只需要 n/2 次遍历

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        i=0
        j=len(numbers)-1
        new_list=[]
        while(j!=i):
            if(numbers[j]+numbers[i]>target):
                j-=1

            if(numbers[i]+numbers[j]<target):
                i+=1
            if(numbers[i]+numbers[j]==target):
                new_list.append(i+1)
                new_list.append(j+1)
                break
        return(new_list)

得到的结果:Your runtime beats 79.21 % of python3 submissions.

2.使用词典追踪,很巧妙的想法

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i in range(len(numbers)):
            if numbers[i] in d:
                return d[numbers[i]]+1,i+1
            else:
                d[target-numbers[i]] = i

结果也很快:You are here!
Your runtime beats 97.11 % of python3 submissions.

3.同样简洁的C++代码

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target)
    {
        int start = 1, end = numbers.size();
        while (numbers[start - 1] + numbers[end - 1] != target){
            if (numbers[start - 1] + numbers[end - 1] > target) end--;
            else start++;}
        return {start, end};
    }
};
//No need to judge if (start < end).

水平还是不行的啊,得好好加油啊!
转载于AITuring的博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值