难度:简单

地址:https://leetcode-cn.com/problems/two-sum/

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

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

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
In [7]:
class Solution:
    def twoSum(self, nums, target):
        '''
        两遍哈希表 时间复杂度 O(n)
        执行用时 : 56 ms, 在Two Sum的Python3提交中击败了89.57% 的用户
        内存消耗 : 14.7 MB, 在Two Sum的Python3提交中击败了7.13% 的用户
        '''
        length = len(nums)
        m = {}
        for i in range(length):
            m[nums[i]] = i
        for i in range(length):
            x = nums[i]
            y = target - x
            if y in m:
                return [i, m[y]]
            
        

s = Solution()
s.twoSum([2, 7, 11, 15], 9)
Out[7]:
[0, 1]
In [8]:
class Solution:
    def twoSum(self, nums, target):
        '''
        一遍哈希表 时间复杂度 O(n)
        执行用时 : 44 ms, 在Two Sum的Python3提交中击败了99.33% 的用户
        内存消耗 : 14 MB, 在Two Sum的Python3提交中击败了56.25% 的用户
        '''
        m = {}
        for i in range(len(nums)):
            x = nums[i]
            y = target - x
            if y in m:
                return [m[y], i]
            m[x] = i
            

s = Solution()
s.twoSum([2, 7, 11, 15], 9)
Out[8]:
[0, 1]