-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathTwoSum.cpp
34 lines (30 loc) · 1.03 KB
/
TwoSum.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
// Problem-Link: https://leetcode.com/problems/two-sum/
#include<vector>
#include<unordered_map>
using namespace std;
class TwoSum {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> sums;
vector<int> results;
for (int i = 0; i < nums.size(); ++i) {
int rem = target - nums[i];
sums[rem] = i;
}
for (int i = 0; i < nums.size(); ++i) {
// Finding the
if (sums.find(nums[i]) != sums.end()) {
// Handling the case when the same element is searced.
if (sums[nums[i]] != i) {
// Ensuring that the results are sorted.
// Pushing the smaller element first.
results.push_back(std::min(i, sums[nums[i]]));
// Pushing the bigger element second.
results.push_back(std::max(i, sums[nums[i]]));
break;
}
}
}
return results;
}
};