(python刷题)leetcode 第1题:两数之和

题目在leetcode上的链接为:
https://leetcode-cn.com/problems/two-sum/

题目描述
在这里插入图片描述
解题思路
使用dict来做
1.将列表nums中的元素值作为key,元素对应下标作为value,建立dict
2.遍历列表nums元素a,判断b = target-a是否在dict中,如果b在dict中且a,b的下标不同,输出a,b下标
在建立dict时可能会出现nums中的元素相同而键值覆盖的情况,但是由于第二次遍历列表nums时,nums中的元素和以前一致,所以键值覆盖的情况并不会产生影响。
下面看一个具体的测试用例:
num3 = [3, 3] target = 9
1.建立dict时,由于3出现了两次,所以建立的dict = {3 : 1}
2.当我们遍历nums时,当遍历到第一个元素nums[0] = 3(把nums[0]看做a)时,我们判断 b = target - nums[0] = 3在dict中,而且a的下标为0,b的下标为1,符合条件,因此可输出[0, 1]得到正确答案。

复杂度分析:
时间复杂度为o(n),需要串行地两次遍历整个数组
空间复杂度为o(n),需要使用dict来存放数组中元素与索引的映射

python代码:

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

发布了37 篇原创文章 · 获赞 6 · 访问量 5403

猜你喜欢

转载自blog.csdn.net/qq_37891889/article/details/104123344