Monday, February 3, 2014

[leetcode][*] 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
Things need to pay attention: 1) the index should + 1; 2) there may be same value contents, and index should not be the same; 3) index1 should > index2
Algorithm:
1. Sort the array and store in another array.
2. search the i and j.
3. find the index in the original array.
My Code:
    int findindex(int val, vector &num, int start){
        for(int i = start; i < num.size(); ++i){
            if(num[i] == val)
                return i;
        }
        return -1;
    }
    vector twoSum(vector &numbers, int target) {
        vector res;
        if(numbers.empty()) return res;
        vector sorted = numbers;
        sort(sorted.begin(), sorted.end());
        int i = 0;
        int j = sorted.size() - 1;
        while(i < j){
            int cur = sorted[i] + sorted[j];
            if(cur > target)
                --j;
            else if(cur < target)
                ++i;
            else{
                int aindex = findindex(sorted[i], numbers, 0);
                int bindex = findindex(sorted[j], numbers, 0);
                if(aindex == bindex){
                    bindex = findindex(sorted[j], numbers, aindex+1);
                }
                if(aindex < bindex){
                    res.push_back(aindex+1);
                    res.push_back(bindex+1);
                }else{
                    res.push_back(bindex+1);
                    res.push_back(aindex+1);
                }
                return res;
            }
        }
    }

No comments:

Post a Comment