1. 程式人生 > >Two sum 兩數之和

Two sum 兩數之和

給定一個數組和一個特定的數,使得陣列中的兩個數等於這個特定的數。找出這兩個數的下標。

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target){
         vector<int> res;
        if(numbers==null||numbers.length<2
) return res; //copy original list and sort vector<int> res copylist ; copylist.assign(numbers.begin(),numbers.end()); copylist.sort(copylist.begin(),copylist.end()); int low = 0; int high = copylist.size()-1; while(low<high){ if
(copylist[low]+copylist[high]<target) low++; else if(copylist[low]+copylist[high]>target) high--; else{ res[0]=copylist[low]; res[1]=copylist[high]; break; } } //find index from original list
int index1 = -1, index2 = -1; for(int i = 0; i < numbers.size(); i++){ if(numbers[i] == res[0]&&index1==-1) index1 = i+1; else if(numbers[i] == res[1]&&index2==-1) index2 = i+1; } res[0] = index1; res[1] = index2; res.sort(res.begin(),res.end()); return res; }
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target)
    {
        int i, sum;  
        vector<int> results;  
        map<int, int> hmap;  
        for(i=0; i<numbers.size(); i++){  
            if(!hmap.count(numbers[i])){  
                hmap.insert(pair<int, int>(numbers[i], i));  
            }  
            if(hmap.count(target-numbers[i])){  
                int n=hmap[target-numbers[i]];  
                if(n<i){  
                    results.push_back(n+1);  
                    results.push_back(i+1);  
                    //cout<<n+1<<", "<<i+1<<endl;  
                    return results;  
                }  

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