LeetCode 1.两数之和

1. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。


示例

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解题思路
一遍哈希:遍历一遍数组,同时判断target - nums[i] 是否在哈希表dic 中。 若在,则返回结果;若不在,则将nums[i]放入哈希表中(用字典实现,key 是 nums[i], value 是 index)


实现代码

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for idx, num in enumerate(nums):
            if (target-num) in dic.keys():
                return [dic[target-num], idx]
            dic[num] = idx

执行用时: 44 ms, 在Two Sum的Python3提交中击败了99.73% 的用户

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。