编程语言
首页 > 编程语言> > (python刷题)leetcode top100第一题:两数之和

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

作者:互联网

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

题目描述
在这里插入图片描述
解题思路
使用dict来做,时间复杂度为o(n),空间复杂度为o(n)
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]得到正确答案。

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

Life will be better 发布了16 篇原创文章 · 获赞 5 · 访问量 4615 私信 关注

标签:遍历,下标,target,nums,python,dict,result,top100,两数
来源: https://blog.csdn.net/qq_37891889/article/details/104123344