LeetCode: Two Sum

扫码查看

题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solutions:
 1 # 方法一:将差后的值作为key存入dict,value为对应在nums的索引,以此来记录遍历过的值,避免暴力解决
 2 class Solution:
 3     def twoSum(self, nums: List[int], target: int) -> List[int]:
 4         _dict = {}
 5         for i in range(len(nums)):
 6             remainning = target - nums[i]
 7             if remainning in _dict:
 8                 return _dict[remainning], i
 9             _dict[nums[i]] = i
10                 
#方法二:使用enumerate将nums转为dict,与方法一同理
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        h = {}
        for i, num in enumerate(nums):
            n = target - num
            if n not in h:
                h[num] = i
            else:
                return [h[n], i]

01-02 13:59
查看更多