Skip to content

Commit a63a19b

Browse files
authored
Create heozeop.cpp
1 parent c5bb52f commit a63a19b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

two-sum/heozeop.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time Complexity: O(nlogn)
2+
// Spatial Complexity: O(nlogn)
3+
4+
class Solution {
5+
public:
6+
vector<int> twoSum(vector<int>& nums, int target) {
7+
bool found = false;
8+
vector<pair<int,int>> temp(nums.size());
9+
10+
for(int i = 0; i < nums.size(); ++i) {
11+
temp[i] = make_pair(nums[i], i);
12+
}
13+
14+
sort(temp.begin(), temp.end());
15+
16+
int start = 0, end = temp.size() - 1, sum;
17+
while(start < end) {
18+
sum = temp[start].first + temp[end].first;
19+
20+
if (sum == target) {
21+
break;
22+
}
23+
24+
if (sum > target) {
25+
--end;
26+
}
27+
28+
if (sum < target) {
29+
++start;
30+
}
31+
}
32+
33+
return vector<int>({temp[start].second, temp[end].second});
34+
}
35+
};

0 commit comments

Comments
 (0)