Monday, April 28, 2014

Two Sum -- Leetcode

Question:
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
Solution:

1. Two pointer method, sort the array firstly. O(nlogn) time + O(1) space.
class Solution {
public:
    bool mycmp(int i, int j){
          return (i<j);
    }

    vector<int> twoSum(vector<int> &numbers, int target) {
              std::sort(numbers.begin(),numbers.end(),mycmp);
              vector<int> res;
              int i=0,j=numbers.size()-1;
              while(i<j){
                   if(numbers[i]+numbers[j]<target) i++;
                   else if(numbers[i]+numbers[j]>target) j++;
                   else {
                       res.push_back(i+1);
                       res.push_back(j+1);
                       break;
                   }
              }  
      }

};

2. Hash Map method. O(n) time + O(n) space.
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers,int target){
        map<int,int> mmap;
        vector<int> res;
       
        for(int i=0;i<numbers.size();++i){
            mmap[numbers[i]]=i;
        }
       
        for(int i=0;i<numbers.size();++i){
            int p = target - numbers[i];
            if(mmap.find(p)!=mmap.end()){
                if(i<mmap[p]){
                    res.push_back(i+1);
                    res.push_back(mmap[p]+1);
                }
                else  if(i>mmap[p]){
                    res.push_back(mmap[p]+1);
                    res.push_back(i+1);
                }
            }
        }
        return res;
    }
};


No comments:

Post a Comment