-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1. Two Sum.cpp
104 lines (83 loc) · 2.28 KB
/
1. Two Sum.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//optimal
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>mp;
for(int i = 0 ; i < nums.size(); i++){
int a = nums[i];
int more = target - a;
//first check if more exit in mp before adding a to mp
if(mp.find(more) != mp.end()){
return {i, mp[more]};
}
//if not then add a to mp and iterate to next
mp[a] = i;
}
return {};
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
unordered_map<int,int>mp;
for(int i = 0;i<n;i++){
mp[nums[i]] = i;
}
for(int i = 0;i<n;i++){
int complement = target - nums[i];
if(mp.find(complement)!=mp.end() && mp[complement]!= i){
return {i,mp[complement]};
}
}
return {};
}
};
//wrong ans for case [3,3] tar = 6 becoz both 3 will mp to same idx
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
unordered_map<int,int>mp;
for(int i = 0 ; i < n ; i++){
mp[nums[i]] = i;
}
sort(nums.begin(),nums.end());
int i = 0 , j = n-1;
while(i < j){
int sum = nums[i] + nums[j];
if(sum > target){
j--;
}
else if(sum == target){
break;
}
else {
i++;
}
}
vector<int>ans;
if(mp.find(nums[i]) != mp.end() ){
ans.push_back(mp[nums[i]]);
}
if(mp.find(nums[j]) != mp.end()){
ans.push_back(mp[nums[j]]);
}
return ans;
}
};
Brute-force approach:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size(),sum =0;
for(int i = 0;i<n;i++){
for(int j = i+1; j<n;j++){
if(target==(nums[i]+nums[j])){
return {i,j};
}
}
}
return {};
}
};