-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.two-sum.cpp
66 lines (51 loc) · 1.48 KB
/
1.two-sum.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @lc app=leetcode id=1 lang=cpp
*
* [1] Two Sum
*/
// @lc code=start
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++) {
// number, index
map.insert({ nums[i], i });
}
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
// find complement among the key
if(map.count(complement)) {
// if below key exist, two sum condition satisfy
if(i != map.at(complement)) {
res = { i, map.at(complement) };
return res;
}
}
// inefficient search
// for(unordered_map<int, int>::iterator it = map.begin(); it != map.end(); ++it) {
// ....
// }
}
return res;
}
vector<int> twoSum_BruteForce(vector<int>& nums, int target) {
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if(nums[i] + nums[j] == target) {
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
// @lc code=end