-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1.two-sum.cpp
More file actions
112 lines (100 loc) · 2.4 KB
/
1.two-sum.cpp
File metadata and controls
112 lines (100 loc) · 2.4 KB
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
103
104
105
106
107
108
109
110
111
112
/*
* @lc app=leetcode id=1 lang=cpp
*
* [1] Two Sum
*/
#include "bits/stdc++.h"
using namespace std;
#define deb(x) cout<<x<<endl;
typedef vector<int> vi;
void print(vi &out){
for(auto x: out) cout<<x<<" ";
cout<<endl;
}
// @lc code=start
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
vector<int> out;
for(int i=0; i<n; ++i){
for(int j=i+1; j<n; ++j){
if(nums[i]+nums[j]==target)
return {i,j};
}
}
map<int,int> seen;
for(int i=0; i<n; ++i){
int req = target - nums[i];
if(seen.count(req)){
return {seen[req], i};
}
seen[nums[i]] = i;
}
return {-1,-1};
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n= nums.size();
vector<int> ans;
for(int i=0;i<n;i++){
int k= target-nums[i];
for(int j=i+1;j<n;j++){
if(nums[j]==k){
ans.push_back(i);
ans.push_back(j);
break;
}
}
if(ans.size()==2)
break;
}
return ans;
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n= nums.size();
vector<int> ans;
unordered_map<int,int> mp;
for(int i=0;i<n;i++){
if(mp.find(target-nums[i])!=mp.end()){
ans.push_back(i);
ans.push_back(mp[target-nums[i]]);
return ans;
}
else
mp[nums[i]]=i;
}
return ans;
}
};
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++){
int req = target- nums[i];
if(mp.find(req) == mp.end()){ // not found
mp[nums[i]] = i; // store the index in map
}
else { // if found in map that the answer
return { mp[req] , i };
}
}
return {-1,-1};
}
};
// @lc code=end
int main(){
Solution sol;
vector<int>nums={2,7,11,15};
int target;
vector<int> out=sol.twoSum(nums,9);
print(out);
return 0;
}