LeetCode 1.TwoSum(哈希)

两种方法

  • 先排序,然后前后夹逼(复杂度n*log(n))。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int s = nums.size();
        pair<int,int>par[s];
        for(int i=0; i<s; ++ i)
        {
            par[i].first = nums[i];
            par[i].second = i;
        }
        sort(par, par+s);
        
        int b = 0, e = s - 1;
        
        while(b < e)
        {
            if(par[b].first + par[e].first > target)
                e --;
            else if(par[b].first + par[e].first < target)
                b ++;
            else
            {
                if(par[b].second > par[e].second)
                    swap(b, e);
                return vector<int>{par[b].second, par[e].second};
            }
        }
    }
};
  • 存在unordered_map,然后直接find.(复杂度n)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int>mp;
        for(int i=0; i<nums.size(); ++i)
            mp[nums[i]] = i;
        for(int i=0; i<nums.size(); ++ i)
        {
            int t = target - nums[i];
            if(mp.find(t) != mp.end() && mp[t] > i)
            {
                return vector<int>{i, mp[t]};
            }
        }
    }
};
posted @ 2017-03-03 09:29  aiterator  阅读(107)  评论(0编辑  收藏  举报