-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtwo_sum.cpp
More file actions
38 lines (32 loc) · 692 Bytes
/
Copy pathtwo_sum.cpp
File metadata and controls
38 lines (32 loc) · 692 Bytes
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
/*Good Problem --
Three approaches
1. O(N^2) -- Brute Force
2. O(N.log(N)) -- 2 Pointer
3. O(N) -- Unordered Set
*/
//2 Pointer technique
bool solve(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int low = 0;
int high = nums.size()-1;
while(low<high){
int sum = nums[low] + nums[high];
if(sum==k){
return true;
}
else if(sum<k) low++;
else high--;
}
return false;
}
// best approach O(n)
bool solve(vector<int>& nums, int k) {
//using set
unordered_set<int> s;
for(int i:nums){
if(s.find(k-i)!=s.end()){
return true;}
s.insert(i);
}
return false;
}