167. Two Sum II

来源:互联网 发布:gson map to json 编辑:程序博客网 时间:2024/06/15 07:35

167. Two Sum II - Input array is sorted

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=9Output: index1=1, index2=2

错误解:
把所有情况都考虑一遍,结果时间超出了限制,貌似时间是O(N^2)

class Solution(object):    def twoSum(self, numbers, target):        """        :type numbers: List[int]        :type target: int        :rtype: List[int]        """        #for i in range(len(numbers)):            #temp = numbers[i]           # for j in range(i+1,len(numbers)):               # if ((numbers[i] + numbers[j]) == target) and i != j:                    #return (i+1), (j+1)

思考:
既然题目给出了答案,那么是否可以把问题转换为搜索问题,即
a - b = c
已知 c 和 a ,在列表中搜索b,
那么这样算法的复杂度就是,便利一遍列表,O(N),再在剩余的列表中搜索b。

正确解1:

class Solution(object):    def twoSum(self, numbers, target):        """        :type numbers: List[int]        :type target: int        :rtype: List[int]        """        for i in xrange(len(numbers)):        l, r = i+1, len(numbers)-1        tmp = target - numbers[i]        while l <= r: #这样就可以在l之后序列中搜索了            mid = l + (r-l)//2            if numbers[mid] == tmp:                return [i+1, mid+1]            elif numbers[mid] < tmp:                l = mid+1            else:                r = mid-1 
# two-pointerdef twoSum1(self, numbers, target):    l, r = 0, len(numbers)-1    while l < r:        s = numbers[l] + numbers[r]        if s == target:            return [l+1, r+1]        elif s < target:            l += 1        else:            r -= 1# dictionary           def twoSum2(self, numbers, target):    dic = {}    for i, num in enumerate(numbers):        if target-num in dic:            return [dic[target-num]+1, i+1]        dic[num] = i
0 0
原创粉丝点击