Two Sum

Code:

O(n):

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

 

O(nxm):

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> res;
        int n=numbers.size();
        for(int i=0;i<n;i++)
            for(int j=i+1;j<n;j++)
                if(numbers[i]+numbers[j]==target){
                    res.push_back(i+1);
                    res.push_back(j+1);
                    return res;
                }
        return res;
    }
};

 

posted @ 2013-10-28 00:24  WinsCoder  阅读(101)  评论(0编辑  收藏  举报