4Sum

来源:互联网 发布:京东数据罗盘多少钱 编辑:程序博客网 时间:2024/05/21 19:00

Given an array S of n integers, are there elements a,b, c, 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,abcd)
  • 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)


Solution:

class Solution {public:    vector<vector<int>> fourSum(vector<int>& nums, int target) {        vector<vector<int> > res;        int len = nums.size();        if(len < 4) return res;        sort(nums.begin(), nums.end());        for(int i = 0; i < len; ++i)        {            if(i != 0 && nums[i] == nums[i-1]) continue;            for(int j = i + 1; j < len; ++j)            {                if(j != i + 1 && nums[j] == nums[j-1]) continue;                int left = j + 1, right = len - 1;                int mid = target - nums[i] - nums[j];                vector<int> v;                v.push_back(nums[i]);                v.push_back(nums[j]);                while(left < right)                {                    int l = nums[left], r = nums[right];                    if(l + r == mid)                    {                        v.push_back(l);                        v.push_back(r);                        res.push_back(v);                        v.pop_back();                        v.pop_back();                        while(nums[++left] == l) ;                        while(nums[--right] == r) ;                    }                    else if(l + r < mid)                    {                        while(nums[++left] == l) ;                    }                    else                    {                        while(nums[--right] == r) ;                    }                }            }        }        return res;    }};


0 0
原创粉丝点击