1. Two Sum [Leetcode][C++]
Mayank Arora
Posted on December 23, 2021
All suggestions are welcome. Please upvote if you like it. Thank you.
Leetcode Problem Link: 1. Two Sum
Brute Force Solution:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//Brute Force Solution TimeO(N^2) & Auxiliary Space O(1)
int length=nums.size();
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(nums[i]+nums[j]==target){
return {i,j};
}
}
}
return {};
}
};
Efficient Solution:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target){
//Efficient Solution TimeO(N) & Auxiliary Space O(N)
int length=nums.size();
unordered_map<int,int> map;
for(auto i=0;i<length;i++){
if(map.find(target-nums[i])!=map.end()){
return {i,map[target-nums[i]]};
}
map[nums[i]]=i;
}
return {};
}
};
All suggestions are welcome. Please upvote if you like it. Thank you.
💖 💪 🙅 🚩
Mayank Arora
Posted on December 23, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.