• 167. Two Sum II


    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.

    My idea:先找出这个target的大致位置,用迭代比大小确定,然后再用迭代逐个相加

    class Solution:
        def twoSum(self, numbers,target):
            i = 0
            while (numbers[i] < target):
                i = i + 1
                if(max(numbers)<=target):
                    i=len(numbers)-1
                    break
            if(i==0):
                return [1,2]
            b = 1
            flag = 0
            c = []
            for a in range(i):
                while (flag == 0 ):
    
                    if (numbers[a] + numbers[b] == target):
                        flag = 1
                        c.append(a + 1)
                        c.append(b + 1)
                        return c
                    b = b + 1
                    if(b >i):
                        break
                b=a+2
            return c

    你以为这样就结束了?

    不,这样耗时太长,所以失败了。。。因为碰到了一个2500char的测试用例

    而且这样写要考虑的情况太多,不简便,不推荐。

    其实学的就是双指针,所以直接双指针就完事了。。

    class Solution:
        def twoSum(self, numbers,target):
            a=0
            b=len(numbers)-1
            while(a<b):
                if(numbers[a]+numbers[b]==target):
                    c=[a+1,b+1]
                    return c
                elif(numbers[a]+numbers[b]<target):
                    a=a+1
                else:
                    b=b-1
    执行用时 : 60 ms, 在Two Sum II - Input array is sorted的Python3提交中击败了62.54% 的用户
    内存消耗 : 13.4 MB, 在Two Sum II - Input array is sorted的Python3提交中击败了95.42% 的用户
  • 相关阅读:
    ATS项目更新(1) CC视图与备份路径同步
    IP地址的正则表达式
    python下载图片(2)
    NS2网络模拟(2)丢包率
    NS2网络模拟(7)homework03.tcl
    python 教程 第二十二章、 其它应用
    python 教程 第十九章、 图形界面编程
    python中string的操作函数
    python中对文件、文件夹的操作
    HTTP状态码(HTTP Status Code)
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10822440.html
Copyright © 2020-2023  润新知