题目:给定一个整数数组nums和一个目标值target,请你在该数组中找出为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:给定nums = [2 , 7, 11, 15],target = 9
因为nums [0] + nums [1] = 2 + 7 = 9
所以返回[0 , 1]
思路:此题我们可以利用字典进行存储,将数组中的元素作为键,将数组元素的索引作为值,判断target减去字典的值是否在字典中即可。击败了99.67%的提交用户
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict_nums = {} for i in range(len(nums)): if target - nums[i] in dict_nums: return [dict_nums[target - nums[i]],i] dict_nums[nums[i]] = i