LeetCode-1- Two Sum

Posted 八行书

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

 

提交结果:

 

 

以上是关于LeetCode-1- Two Sum的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 1.Two sum

Leetcode 1. Two Sum (Python)

LeetCode #1 - Two Sum

1. 两数之和 [leetcode 1: Two Sum]

1. 两数之和 [leetcode 1: Two Sum]

Leetcode-1 Two Sum