We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a51dcca commit f01aeb3Copy full SHA for f01aeb3
1 file changed
two-sum/dylan-jung.cpp
@@ -1,17 +1,16 @@
1
+// TC: O(N), SC: O(N)
2
+
3
class Solution {
4
public:
5
vector<int> twoSum(vector<int>& nums, int target) {
- vector<tuple<int, int>> arr;
- arr.reserve(nums.size());
6
+ unordered_map<int, int> m;
7
for(int i = 0; i < nums.size(); i++) {
- arr.push_back({nums[i], i});
8
+ m[nums[i]] = i;
9
}
- int s = 0; int e = nums.size()-1;
10
- sort(arr.begin(), arr.end());
11
- while(s < e) {
12
- if(get<0>(arr[s]) + get<0>(arr[e]) > target) e-=1;
13
- else if (get<0>(arr[s]) + get<0>(arr[e]) < target) s+=1;
14
- else return {get<1>(arr[s]), get<1>(arr[e])};
+ for(int first = 0; first < nums.size(); first++) {
+ if(m.count(target - nums[first]) > 0 && first != m[target - nums[first]]) {
+ return {first, m[target - nums[first]]};
+ }
15
16
return {};
17
0 commit comments