-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.cpp
More file actions
34 lines (33 loc) · 890 Bytes
/
twoSum.cpp
File metadata and controls
34 lines (33 loc) · 890 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
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
vector<int> result;
for(int i = 0; i < len - 1; i++){
for(int j = i + 1; j < len; j++){
if(nums[i] + nums[j] == target){
result.push_back(i);
result.push_back(j);
break;
}
}
}
return result;
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
vector<int> ans(2);
for (int i = 0; i < nums.size(); i++) {
if (m.find(target - nums[i]) != m.end()) {
ans[0] = m[target - nums[i]];
ans[1] = i;
return ans;
}
m[nums[i]] = i;
}
return ans;
}
};