1. Two Sum [Leetcode][C++]

mayankdv

Mayank Arora

Posted on December 23, 2021

1. Two Sum [Leetcode][C++]

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 {}; 
    }
};

Enter fullscreen mode Exit fullscreen mode

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 {};
    }
};

Enter fullscreen mode Exit fullscreen mode

All suggestions are welcome. Please upvote if you like it. Thank you.

💖 💪 🙅 🚩
mayankdv
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.

Related