【leetcode】 4 sum

来源:互联网 发布:uvwxyz.xyz index.php 编辑:程序博客网 时间:2024/04/27 14:19

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)
mit上说有O(n^2logn)的解法,没看懂…… 只弄了这个O(n^3)的,基本解法就是在3 sum外面再套一层for循环。

class Solution {public:    vector<vector<int> > fourSum(vector<int> &num, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<vector<int> > results;        if (num.size()<3)            return results;        vector<int> result;        result.resize(4);        sort(num.begin(),num.end());            int len = num.size();        for (int i = 0; i<len-3; i++){            if (i>0 && num[i]==num[i-1])                continue;            int num_1 = num[i];            result[0] = num_1;                        for (int j = i+1; j < len-2; j++){                if (j>i+1 && num[j]==num[j-1])                    continue;                int num_2 = num[j];                result[1] = num_2;                int left = j+1;                int right = len-1;                int value = num_1+num_2;                while(left<right){                    if (left!=j+1&&num[left]==num[left-1]){                        left++;                        continue;                    }                    if (right!=len-1&&num[right]==num[right+1]){                        right--;                        continue;                    }                                        if (value+num[left]+num[right] == target){                        result[2] = num[left];                        result[3] = num[right];                        results.push_back(result);                        left++;                        right--;                    }                    else if (value+num[left]+num[right] < target){                        left++;                    }                     else                        right--;                }            }        }        return results;    }};

1. 亲,记得sort啊,3 sum往,3 sum closest忘,现在还是忘!!!


2. 几个去重复,很重要!
也可以用hash table来去重复,个人觉得不如这样效率高








原创粉丝点击