LeetCode-1- Two Sum

时间:2022-05-08
本文章向大家介绍LeetCode-1- 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.

Example:

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

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

简言之,查找给定数组内两个数,使得两数和为给定的target

思路:

  遍历给定数组,用一个哈希表存放已经遍历过的值,key是nums中的值,value是其位置索引。

  对于当前遍历的nums[i],查找哈希表中是否存在target-nums[i],若存在,则返回二者索引,否则将(key=nums[i],value=i)放入哈希表中,继续遍历

时间复杂度:O(n)

python代码如下,已AC:

 1 class Solution(object):
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         dictMap = {}
 9         for index, value in enumerate(nums):
10             if target - value in dictMap:
11                 return [dictMap[target - value] , index ]
12             dictMap[value] = index

提交结果: