forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-sum(AC).cpp
31 lines (29 loc) · 824 Bytes
/
2-sum(AC).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// The O(n) solution by hashing
#include <unordered_map>
using namespace std;
class Solution {
public:
/*
* @param numbers : An array of Integer
* @param target : target = numbers[index1] + numbers[index2]
* @return : [index1+1, index2+1] (index1 < index2)
*/
vector<int> twoSum(vector<int> &nums, int target) {
vector<int> &a = nums;
vector<int> ans;
int n = a.size();
unordered_map<int, int> um;
unordered_map<int, int>::iterator it;
int i;
for (i = 0; i < n; ++i) {
it = um.find(target - a[i]);
if (it != um.end()) {
ans.push_back(it->second + 1);
ans.push_back(i + 1);
break;
}
um[a[i]] = i;
}
return ans;
}
};