0%

Leet code: Two Sum[Easy]

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].
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <map>
#include <iterator>

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
vector<int> v(2);
map<int, int>::iterator iter;
for(int i = 0; i < nums.size(); ++i){
iter = m.find(target - nums[i]);
if(iter != m.end()){
v[0] = iter->second, v[1] = i;
break;
}
m[nums[i]] = i;
}
return v;
}
};
1
2
Runtime: 12 ms, faster than 93.28% of C++ online submissions for Two Sum.
Memory Usage: 10.1 MB, less than 54.10% of C++ online submissions for Two Sum.
思路
  • 遍历数组,插入<value, index>之前查找是否存在key=value(避免出现重复的key)
  • 存在则return [index, i], 不存在继续遍历