(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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值