forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-sum.cpp
More file actions
25 lines (21 loc) 路 643 Bytes
/
Copy path2-sum.cpp
File metadata and controls
25 lines (21 loc) 路 643 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Time: O(n)
// Space: O(n)
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) {
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); ++i) {
// Check if "target - nums[i]" exists or not
if (hash.find(target - nums[i]) != hash.end()) {
return {hash[target - nums[i]] + 1, i + 1};
}
hash[nums[i]] = i;
}
return {};
}
};