Friday, March 11, 2022

1. Two Sum

 Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

 

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

 

Follow-up: Can you come up with an algorithm that is less than O(n2time complexity?



Soluation:


In JavaScript:

var twoSum = function(nums, target) {
    let ans = new Array();
    for(let i=0;i<nums.length;i++){
        for(let j=i+1;j<nums.length;j++){
            if(target == nums[i]+nums[j]){
                ans[0]= i;
                ans[1] = j;
                break;
            }
        }
    }
    
   return ans; 
};
In C++:

3 Approches Worst to Best: 

Time - O(n^2)

Space - O(1)

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) 
	{
		vector<int> v;
		for(int i=0;i<nums.size();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;
				}
			}
        }
        return v;
    }
};

Time - O(nlogn)
Space - O(n)

class Solution {
public:
    vector<int> twoSum(vector<int>& a, int k) 
	{
		vector<pair<int,int>> v;
		int n=a.size(),x,y;
		for(int i=0;i<a.size();i++)
			v.push_back({a[i],i});
		sort(v.begin(),v.end());
		int i=0,j=n-1;
		while(i<j)
		{
			if(v[i].first+v[j].first==k)
			{
				x=v[i].second;
				y=v[j].second;
				break;                
			}
			if(v[i].first+v[j].first<k)
				i++;
			if(v[i].first+v[j].first>k)
				j--;
        }
        return {x,y};        
    }
};

Time - O(n)
Space - O(n)

class Solution {
public:
    vector<int> twoSum(vector<int>& a, int k) 
	{
		vector<int> v;
		int n=a.size();
		map<int,int> m;
		for(int i=0;i<n;i++)
		{
			if(m.count(k-a[i]))
			{
				v.push_back(m[k-a[i]]);
				v.push_back(i);
				return v;
			}
			else
				m[a[i]]=i;
		}
        return v;        
    }
};

No comments:

Post a Comment