LeetCode(Python版)——1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

1.暴力破解,时间复杂度为 O(n^{2})

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

 2.使用字典dict,时间复杂度为O(n),执行2次迭代的字典

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        index = 0
        numDict = {}
        for e in nums:
            numDict[e] = index
            index += 1
        for i in range(len(nums)):
            otherNum = target - nums[i]
            if otherNum in numDict.keys() and numDict[otherNum] != i:
                return [i, numDict[otherNum]]

3.使用字典dict,时间复杂度为O(n),执行1次迭代的字典

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        numDict = {}
        for i in range(len(nums)):
            otherNum = target - nums[i]
            if otherNum in numDict.keys() and numDict[otherNum] != i:
                return [i, numDict[otherNum]]           
            numDict[nums[i]] = i

总结:

1.最开始使用的是暴力破解的方法, 遇到的问题是range()方法使用错误,导致出现一次提交错误。range(i, j),表示生成i<=N<j之间的一组整数,此题的一对解[i, j]中i与j是不同的,即不能使用num[i]本身构成解,后面两种使用字典dict出错也是因为未考虑这点。

2.使用字典时未考虑num[i]与num[j]相同的情况,但是因为在使用方法2时,直接通过,所以在实现方法3时出现问题。字典中键值相同时会更新为最新出现的值。例如nums = [3, 3],target = 6,在使用方法2构造dict时,numDict[3] = 1,因此当num[0] 时另一个数otherNum = 3,求得索引index = 1,这样就构成了解,因此也忽略了当存在值相同的情况。使用方法3时,因为采用一次迭代,所以需要边插值,边解另一个值otherNum,在第一次实现这个算法时,我先将值更新到字典中,导致当nums = [3, 3]时,因为numDict[3] = 1 = i,所以出现返回值为NULL的情况,出现错误,正确的做法是先检查otherNum是否存在于字典中,然后再进行插值,这样当i = 1时,numDict[3] = 0,避免出错。因为此题考虑的只有一组正确解,因此这样做是没有问题的。当存在多个解时,如nums = [3, 3, 3],方法2返回的是[0, 2],方法3返回的是[1, 0]。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值