两数之和

两数之和

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

自己解答

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic={} 
        find=0
        res=[]
        for i in range(len(nums)):
            dic[i]=nums[i]
        # dic1.clone
        dic1 = dic.copy() 
        for key,value in dic.items():
            # print("==============")
            # print(key ,  value)
            find=target-value # 计算需要查找的值
            # print('find :',find)
            dic1.pop(key) #查找过了可以移除
            # print(dic1)
            if find in dic1.values():
            	# list(dic1.keys())[list(dic1.values()).index(find)] 根据 find 来查找再dic1中的键
                res=(key,list(dic1.keys())[list(dic1.values()).index(find)])
                break
        return res

执行用时:524 ms, 在所有 Python 提交中击败了55.26% 的用户
内存消耗:15.2 MB, 在所有 Python 提交中击败了5.01% 的用户

大神解答

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hash_map = {}
        for index, number in enumerate(nums):
            another_number = target - number
            if another_number in hash_map:
                # print([hash_map[another_number],index])
                return [hash_map[another_number],index]
            else:
                hash_map[number] = index

执行用时:16 ms, 在所有 Python 提交中击败了97.45% 的用户
内存消耗:13.6 MB, 在所有 Python 提交中击败了23.75% 的用户

个人理解
只用声明一个dict ,在遍历nums的同时,查找目标值,如果在hash_map中没有目标值的话就把当前遍历到index, number 加入到hash_map中。
收获
enumerate 关键字的用法,之前没有学习过此关键字

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值