码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "4Sum"

时间:2014-08-18 13:00:32      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   amp   

Similar strategy could be applied to 4Sum, as 2sum to 3sum, but that‘ll be O(n^3). Instead of 3 + 1, we can also divide it into 2 + 2. So the problem becomes finding another pair - yes hashmap.

class Solution {
public:
    struct Rec
    {
        Rec() : i0(0), i1(0) {}
        Rec(int ri0, int ri1) : i0(ri0), i1(ri1) {}
        bool equals(Rec &r)
        {
            return i0 == r.i0 || i1 == r.i1 || i0 == r.i1 || i1 == r.i0;
        }
        int i0;
        int i1;
    };
    vector<vector<int>> fourSum(vector<int> &num, int target) {        
        vector<vector<int>> ret;
        if(num.size() < 4) return ret;
// Make pair size_t cnt = num.size(); unordered_map<int, vector<Rec>> hm; for (size_t i = 0; i < cnt - 1; i ++) for (size_t j = i + 1; j < cnt; j++) { int sum2 = num[i] + num[j]; if (hm.find(sum2) == hm.end()) { vector<Rec> v; v.push_back(Rec(i, j)); hm.insert(make_pair(sum2, v)); } else { hm[sum2].push_back(Rec(i, j)); } } //  Match unordered_set<string> done; auto it = hm.begin(); for (; it != hm.end(); it++) { int sum1 = it->first; auto it2 = hm.find(target - sum1); if (it2 != hm.end()) { for (int i = 0; i < it2->second.size(); i ++) for (int j = 0; j < it->second.size(); j ++) { Rec &r1 = it->second[j]; Rec &r2 = it2->second[i]; if (!r1.equals(r2)) { vector<int> cv; cv.push_back(num[r1.i0]); cv.push_back(num[r1.i1]); cv.push_back(num[r2.i0]); cv.push_back(num[r2.i1]); std::sort(cv.begin(), cv.end()); string str; for (int i = 0; i < cv.size(); i++) { str += std::to_string(cv[i]); } if (done.find(str) == done.end()) { ret.push_back(cv); done.insert(str); } } } } } return ret; } };

 

LeetCode "4Sum",布布扣,bubuko.com

LeetCode "4Sum"

标签:style   blog   color   io   for   ar   div   amp   

原文地址:http://www.cnblogs.com/tonix/p/3919254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!