Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CppSolutionTwoSum.cpp #212

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions Two Sum/twoSum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Question Link :- https://leetcode.com/problems/two-sum/

// Below is Solution

//1st Approach
// Time Complexity :- O(n^2)

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v;
for(int i=0;i<nums.size()-1;i++){
for(int j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
v.push_back(i);
v.push_back(j);
}
}
}
return v;
}
};

//OR

//2nd Approach
//HashMaps
//Time Complexity-O(n)

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> m;
for(int i=0;i<nums.size();i++){
int x=nums[i];
int y=target-x;
if(m.find(y)!=m.end()){
return {i,m[y]};
}
m[nums[i]]=i;
}
return {-1,-1};
}
};