-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec_14.cpp
64 lines (51 loc) Β· 1.46 KB
/
lec_14.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
vector<int>ans(2,-1);
for(int i = 0 ; i< n ; i++)
{
for(int j = i+1 ; j<n;j++){
if(nums[i]+nums[j] == target && i !=j){
ans.push_back(i);
ans.push_back(j);
return {i,j};
}
}
}
return ans;
}
};
//
#include <bits/stdc++.h>
using namespace std;
vector<int> twoSum(int n, vector<int> &arr, int target) {
unordered_map<int, int> mpp;
for (int i = 0; i < n; i++) {
int num = arr[i];
int moreNeeded = target - num;
if (mpp.find(moreNeeded) != mpp.end()) {
return {mpp[moreNeeded], i};
}
mpp[num] = i;
}
return { -1, -1};
}
// two pointer
class Solution {
public:
vector<int> twoSum(vector<int>& arr, int target) {
int n = arr.size();
sort(arr.begin() , arr.end());
int left = 0 , right = n-1;
while(left <right){
int sum = arr[left] + arr[right];
if(sum == target){
return {left , right};
}
else if( sum<target) left ++;
else right --;
}
return {-1,-1};
}
};