LeetCode 刷题小本本Day1 Two Sum(hashmap)

(1) Two Sum

题目:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
给定一个list和target,找到list中加起来等于target的索引,不能重复使用值。

我的答案:

    def twoSum1(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in nums:
            sub = target - i
            nums_copy = nums.copy()
            nums_copy.remove(i)
            if sub in (nums_copy):
                index_i = nums.index(i)
                index_j = nums.index(sub,index_i+1)
                break
        return [index_i, index_j]

遇到的问题:

  1. 怎么解决“不允许重复值”:拷贝一个list;获取索引时从index_i+1开始找。

参考答案1:

    def twoSum(self, nums, target):
        hashmap = {}
        for i in range(len(nums)):
            complement = target - nums[i]
            if complement in hashmap:
                return [i, hashmap[complement]]
            hashmap[nums[i]] = i

更好的处理了不能重复使用相同值的问题:

  • 逻辑:找当前值和出现在他之前的值之和,有没有等于target的。
  • 这个地方建立了一个hashmap,相当于字典啦,不过不是一次性建立的,可以解决“一个值不能用两次的问题”。

参考答案 2:

class Solution:
    def twoSum(self, nums, target):
        h = {}
        for i, num in enumerate(nums):
            n = target - num
            if n not in h:
                h[num] = i
            else:
                return [h[n], i]

这个地方把list转成了dict,然后也用了hashmap的思路。

收获:

  1. list变量获取索引:num.index(i)
  2. list 变量删除元素 nums.remove(i),返回的是NoneType,所以直接用nums就好啦。
  3. list直接赋值就是对象的引用(别名);浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
  4. list转dictionary,需要利用enumerate(将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列):dict(list(enumerate(nums)))。也可以直接for i, num in enumerate(nums)
  5. hashmap的形式查找,可以避免出现重复值。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值