Skip to content

Latest commit

 

History

History
14 lines (13 loc) · 587 Bytes

File metadata and controls

14 lines (13 loc) · 587 Bytes

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

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        #构造哈希表来求解
        hashmap = {}
        for i, num in enumerate(nums):
            if target - num in hashmap:
                #如果在哈希表里,直接返回下标
                return [i, hashmap[target-num]]
            #记录该元素的下标到哈希表中
            hashmap[num] = i