Saturday, February 16, 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
*/
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> result;
        int startIndex;
        int endIndex;
        int addition;
        for(vector<int>::iterator it = numbers.begin(); it <(numbers.end()-1); it++){
         for(vector<int>::iterator jt = it+1; jt < numbers.end(); jt++){
            addition = *it + *jt;
            if (addition == target) {
            startIndex = distance(numbers.begin(), it)+1;
            endIndex = distance(numbers.begin(), jt)+1;
            result.push_back(startIndex);
            result.push_back(endIndex);
            return result;
            }
         }
        }
        return result;
    }

--- DP way
vector<int> twoSum(vector<int> &numbers, int target) {

// Start typing your C/C++ solution below

// DO NOT write int main() function

int start = 1;

int end = 2;

int size = numbers.size();



findTarget(numbers, 1, 2, start, end, size, target);

 
vector<int> result;

if(!(start==1 && end==2 && numbers[0]+numbers[1]!=target)){



result.push_back(start);

result.push_back(end);

}

 
return result;



}



 
void findTarget(vector<int> &numbers, int i, int j, int & start, int & end, int const size, int const target){

if(i >= j|| i > size-1 || j> size) return;

int addition = numbers[i-1] + numbers[j-1];

if (addition == target) {



start = i;

end = j;

 
return;



}

findTarget(numbers, i+1, j, start, end, size, target);

findTarget(numbers, i, j+1, start, end, size, target);

}
 

No comments:

Post a Comment