Leetcode 刷题 - 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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


根据题意,给出一个排序好的list,一个目标值,假设必然会有一个结论的情况下,找出从小到大的两个数字。


如果是搜索的角度考虑,必然会想到binary sreach。

但是时间复杂度方面并没有使用两个指针,从两端往中间扫来的快,时间复杂度是O(n),扫一遍,空间复杂度O(1)。


class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(numbers)):
            l, r = 0, len(numbers)-1 # 覆盖全部的index
            tmp = target - numbers[i]
            
            while l < r:
                sum = numbers[l] + numbers[r] 
                if sum < target: # 最左往右移动
                    l += 1
                elif sum > target: # 最右往左移动
                    r -= 1
                else:
                    return l + 1, r + 1 # 根据题意,返回list的index+1


=============

用python的dictionary

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for i in range(len(numbers)): # list值作为key,index作为value
            if numbers[i] not in dic:
                dic[numbers[i]] = [i]
            else:
                dic[numbers[i]] += [i] # 如果有重复的,往value数组里继续添加

        for key in dic:
            if (target - key) in dic:
                if key == (target - key): # 特殊情况,如果target由两个相同的值相加,那么肯定会有一个value list存有至少两个不同的index值
                    return sorted([dic[key][0] + 1, dic[key][1] + 1])
                return sorted([dic[key][0] + 1, dic[target-key][0] + 1])

唯一要特别注意的是,python的dictionary的排序并不是按照从小到大顺序的。(我也没懂是怎么排序的。。)


================

binary search 分析,时间复杂度O(nlogn)

class Solution(object):
    def twoSum(self, numbers, target):
        for i in xrange(len(numbers)):
            l, r = i+1, len(numbers)-1 # 每次都从i开始
            tmp = target - numbers[i]
            
            while l <= r:
                mid = l + (r-l)/2 # (r-l)/2是现在这段的一半,加上l,就是现在这段的mid的index
                if numbers[mid] == tmp:
                    return [i+1, mid+1] 
                elif numbers[mid] < tmp:
                    l = mid + 1
                else:
                    r = mid - 1




用了Python自帶的enumerate()方法。

class Solution4(object):
    def twoSum(self, numbers, target):

        dic = {}
        for i, num in enumerate(numbers): # use enumerate function
            if target-num in dic:
                return [dic[target-num]+1, i+1]
            dic[num] = i




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值