【leetcode】 4 sum

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來去重複,個人覺得不如這樣效率高








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章