-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo sum.cpp
More file actions
31 lines (30 loc) · 803 Bytes
/
Two sum.cpp
File metadata and controls
31 lines (30 loc) · 803 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
//Two sum using brute force
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i=0;i<nums.size()-1;i++){
for(int j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
return {i,j};
}
}
}
return {};
}
};
//Two sum using hashing
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
unordered_map<int,int>numMap;
for(int i=0;i<n;i++){
int comp=target-nums[i];
if(numMap.count(comp)){
return{numMap[comp],i}; //it gives index of comp using hashtable orelse it stores in hastable if not present current comp
}
numMap[nums[i]]=i;
}
return {};
}
};