题目

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:

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

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

思路

可以建一个map,存储遍历过的数。当遇到新的数字时,判断map里头有没有 target 与该数字的差。

解答

Cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> lookup;
for (int i = 0; i < nums.size(); ++i) {
if (lookup.count(target - nums[i])) {
return {lookup[target - nums[i]], i};
}
lookup[nums[i]] = i;
}
return {};
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i in range(len(nums)):
if (target-nums[i]) in lookup:
return (lookup[target-nums[i]], i)
else:
lookup[nums[i]] = i

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let lookup = new Map();
for (let i=0; i<nums.length; ++i) {
if (lookup.has(target - nums[i])) {
return [lookup.get(target-nums[i]), i];
} else {
lookup.set(nums[i], i);
}
}
};

复杂度分析

  • 时间复杂度:\(O(n)\)
  • 空间复杂度:\(O(n)\)

Comments