LeetCode-18:4 Sum (四数的和)

题目:4 Sum

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

Note:

  • The solution set must not contain duplicate quadruplets.

例子:

Given array nums = [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]
]

问题解析:

给定数组,返回数组中和为target的四元组。

链接:

思路标签

算法:排序 + 双指针

解答:

  • 以LeetCode-15 & 16 的思想,我们使用两个循环遍历给出四元组中的前两个候选,然后以双指针的形式选择剩下的两个候选;
  • 因为数组是排序过的,所以我们可以分别在第一和第二个循环中判断当前连续四个(三个)以及当前候选和最后的三个(两个)候选的和与target比较,选择循环的跳过和跳出;
  • 同样,我们需要注意循环中第一和第二个候选的重复问题,连续相同的候选选择跳过操作;同样也对符合条件的左右指针值进行跳过操作。
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int> > ret;
        int n = nums.size();
        if(n<4) return ret;
        sort(nums.begin(), nums.end());
        for(int i=0; i<n-3; ++i){
            if(i>0 && nums[i]==nums[i-1]) continue;
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target) break;
            if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1] < target) continue;
            for(int j=i+1; j<n-2; ++j){
                if(j>i+1 && nums[j]==nums[j-1]) continue;
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2] > target) break;
                if(nums[i]+nums[j]+nums[n-2]+nums[n-1] < target) continue;
                int l = j+1, r = n-1;
                while(l<r){
                    int tempsum = nums[i]+nums[j]+nums[l]+nums[r];
                    if(tempsum < target) l++;
                    else if (tempsum > target) r--;
                    else{
                        ret.push_back(vector<int>{nums[i], nums[j], nums[l], nums[r]});
                        do{
                            l++;
                        }while(nums[l] == nums[l-1] && l<r);
                        do{
                            r--;
                        }while(nums[r] == nums[r+1] && l<r);
                    }
                }
            }
        }

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