LeetCode No.18 4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)

题目意思很明确。又是K-Sum问题。之前有两道3Sum和3Sum Closest,都类似,排序后利用Symbol Table的高查找效率来达到一个较高的时间复杂度。

这个题也一样,先用N平方的复杂度将所有的数对以及他们的和都添加进Symbol Table,再用N平方的复杂度遍历所有添加进去的数对,然后查找是否存在和的相反数。

这题我做了一早上,都超时。当时百思不得其解。难道还能有更高效的算法么?

后来发现,我使用的是std::multimap来做Symbol Table。我同学告诉我,multimap是 Red-Black Tree Implementation,所以查找效率是logN。

于是使用了unordered_multimap,查找效率应该是O(1),终于解决了问题。

正好学Princeton的Algorithm学到了红黑树,也正好碰到这个问题,加深了对这个问题了理解。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int> &num, int target) {
        int i, j, sz = num.size();
        vector<vector<int>> res;
        vector<int> t;
        set<vector<int>> r;

        typedef unordered_multimap<int, pair<int, int>> MAP;
        MAP m;

        if (num.size() < 4) return res;

        sort(num.begin(), num.end());

        for (i = 0; i < sz - 1; i++) {
            for (j = i + 1; j < sz; j++) {
                m.insert(pair<int, pair<int, int>>(num[i] + num[j], make_pair(i, j)));
            }
        }

        for (MAP::iterator it = m.begin(); it != m.end(); it++) {
            if (m.find(target - it->first) != m.end()) {
                pair<MAP::iterator, MAP::iterator> p = m.equal_range(target - it->first);
                for (MAP::iterator pit = p.first; pit != p.second; pit++) {
                    if (pit->second.first > it->second.second) {
                        t.push_back(num[it->second.first]);
                        t.push_back(num[it->second.second]);
                        t.push_back(num[pit->second.first]);
                        t.push_back(num[pit->second.second]);
                        sort(t.begin(), t.end());
                        r.insert(t);
                        t.clear();
                    }
                }
            }
        }

        for (set<vector<int>>::iterator it = r.begin(); it != r.end(); it++) {
            res.push_back(*it);
        }

        return res;
    }
};

 

posted @ 2015-01-27 13:41  _Anonyme  阅读(123)  评论(0编辑  收藏  举报