DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Mayank Arora
Mayank Arora

Posted on

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.

Top comments (0)

Tired of sifting through your feed?

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.