Skip to content

Commit 79f2ab4

Browse files
committed
two sum solution
1 parent 2b03b71 commit 79f2ab4

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

two-sum/ys-han00.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#include <bits/stdc++.h>
2+
3+
class Solution {
4+
public:
5+
vector<int> twoSum(vector<int>& nums, int target) {
6+
vector<pair<int, int>> num_idx;
7+
for(int i = 0; i < nums.size(); i++)
8+
num_idx.push_back({nums[i], i});
9+
10+
sort(num_idx.begin(), num_idx.end());
11+
12+
int left = 0, right = nums.size() - 1;
13+
while(1) {
14+
if (num_idx[left].first + num_idx[right].first == target)
15+
return vector<int>({num_idx[left].second, num_idx[right].second});
16+
if(num_idx[left].first + num_idx[right].first < target) left++;
17+
else right--;
18+
}
19+
}
20+
};

0 commit comments

Comments
 (0)