LeetCode 1两数之和

好久没刷LeetCode了,这几个月打算重新补一下算法,那就从第一题重新刷了,顺便写一组解题报告

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

  1. 我A了这题四次,每一次都是一次性能优化
    一开始拿到题目,自然而然就想到直接O(n^2),就是直接遍历列表,取一个值,然后再遍历一次列表,找到两个相加等于目标数的值,返回下标即可。
#战胜 27.32 % 的 python 提交记录
#执行用时3992 ms
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i + 1,len(nums)):
                if (nums[i] + nums[j] == target):
                    return [i,j]
  1. 这种速度显然我们是不会满意的,那么我又思考了一下,就是遍历列表一次,然后用目标值和nums[i]做差,然后得出差的值,并使用python的in关键字查看差的值是否在列表中(前提是差值的下标和i不相等),如果有这个情况存在,那么我们使用nums.index(tgt)返回我们要找的和tgt相等的值的下标。然后返回。
#战胜 54.29 % 的 python 提交记录
#执行时间916 ms
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            tgt = target - nums[i]
            if tgt in nums:
                if nums.index(tgt) != i:
                    if nums.index(tgt) > i:
                        return [i,nums.index(tgt)]
                    else:return[nums.index(tgt),i]
                else:
                    continue

可以看到速度优化了不少,但是还是不够,我没想到更好的办法,于是看了下排名较高的大佬的题解
他们的代码是这样的

#战胜 98.36 % 的 python 提交记录
#执行时间28 ms
class Solution:
    def twoSum(self,nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(nums)
        d = {}
        for x in range(n):
            a = target - nums[x] 
            if nums[x] in d:
                return d[nums[x]],x
            else:
                d[a] = x

代码非常简单,创建了一个字典d,遍历一次列表,每过一项,如果不满足对应项的值在字典的键中找到,那么就把对应项的值和目标值的差作为键,下标作为值塞到字典里,直到找到对应的项在字典的键中找到,那么返回[d[nums[x]],x]。可以看到算法已经优化到极致了。

posted @ 2019-03-11 01:09  ayang818  阅读(109)  评论(0编辑  收藏  举报