-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path001_two_sum.cpp
More file actions
54 lines (50 loc) · 1.55 KB
/
Copy path001_two_sum.cpp
File metadata and controls
54 lines (50 loc) · 1.55 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* @Author: wangxiaobo
* @Date: 2015-01-03 11:35:18
* @Last Modified by: wangxiaobo
* @Last Modified time: 2015-01-03 12:08:21
*/
#include <utils.h>
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> indices;
unordered_map<int, size_t> indices_map(numbers.size() / 2);
for (size_t i = 0; i < numbers.size(); i++) {
indices_map[numbers[i]] = i;
}
for (size_t i = 0; i < numbers.size(); i++) {
int another = target - numbers[i];
if (indices_map.count(another) > 0) {
size_t j = indices_map[another];
if (i != j) {
if (i < j) {
indices.push_back(i);
indices.push_back(j);
} else if (i > j) {
indices.push_back(j);
indices.push_back(i);
}
break;
}
}
}
return indices;
}
};
TEST(_0001, TwoSum) {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
Solution s;
vector<int> res = s.twoSum(nums, target);
// if (!res.empty()) {
// cout << "index1=" << res[0] << ", index2=" << res[1] << endl;
// } else {
// cout << "not found" << endl;
// }
ASSERT_TRUE(res.size() == 2 && (res[0] == 0) && (res[1] == 1));
target = 6;
vector<int> case2 = {3, 2, 4};
res = s.twoSum(case2, target);
ASSERT_TRUE(res.size() == 2 && (res[0] == 1) && (res[1] == 2));
}