1.Two Sum

两种方法:

  • 直接遍历,复杂度为 \(O(n^2)\)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> a;
        for(int i = 0; i < nums.size(); i++){
            for(int j = i+1; j < nums.size(); j++){
                if(nums[i] == target - nums[j]){
                    a.push_back(i);
                    a.push_back(j);
                }
            }
        }
        return a;
    }
    
};
  • 利用map,复杂度为 \(O(n)\)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> a;
        vector<int> res;
        for(int i = 0; i < nums.size(); i++){
            if(a.find(target-nums[i]) == a.end()){
                a[nums[i]] = i;
            }
            else{
                res.push_back(a[target-nums[i]]);
                res.push_back(i);
                return res;
            }   
        }
        return res;
    }
};
posted @ 2017-06-05 22:40  UniMilky  阅读(107)  评论(0编辑  收藏  举报