[leetcode] 1. 两数之和

难度:easy.

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

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

方法一:暴力解。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

结果肯定不是很理想:

执行用时 :3580 ms, 在所有 python 提交中击败了19.99%的用户.
内存消耗 :12.7 MB, 在所有 python 提交中击败了26.03%的用户.

方法二:使用哈希表。
哈希表最大的优点,就是把数据的存储和查找消耗的时间大大降低,而代价仅仅是消耗比较多的内存。

现在的暴力解法的时间复杂度非常大。所以使用哈希表存储已经检查过的元素,并记录下对应的索引(因为这道题的返回值是索引,所以哈希表的key是元素,value是索引)。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i in range(len(nums)):
            if target - nums[i] not in dict:
                dict[nums[i]] = i
            else:
                return [dict[target-nums[i]], i]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。