Sunday, August 18, 2013

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

There are 2 ways to solve this in better than O(n^2)
1. Sort the given array. Take 2 pointers, one at the start, other at the end. 
if their sum exceeds the target, decrement the end pointer. If their sum is less than the target increment the start pointer.Do this until you find a pair.
Takes no extra space. Time Complexity O(nlogn).

2. The other approach is to use map. Map the elements of the array. Take the elements one by one, subtract it from the target and search for the (target-element) part in the map.
Time and Space Complexity O(n).

Code :

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        map<int, int> mymap;
        int i;
        int toSearch;
        for(  i=0; i<numbers.size();++i)
        mymap[numbers[i]]= i;
        for(i=0; i<numbers.size(); ++i)
        {
            toSearch = target-numbers[i];
            if(mymap.find(toSearch)!=mymap.end())
            {
                result.push_back(i+1);
                result.push_back(mymap[toSearch]+1);
            }
        }
    return result;
    }
}; 
 

No comments:

Post a Comment