18. 4Sum

作者: weego | 来源:发表于2018-04-06 00:03 被阅读0次

Description

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: 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

  • 排序夹逼法
    和15. 3Sum类似,只不过多加了一层循环而已,要保证结果不重复
vector<vector<int> > fourSum(vector<int> &nums, int target) {  
    vector<vector<int> > ret;
    if (nums.size() < 4) {
        return ret;
    }
    sort(nums.begin(), nums.end());
    for (int i = 0; i < nums.size() - 3; ++i) {
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        for (int j = i + 1; j < nums.size() - 2; ++j) {
            if (j > i + 1 && nums[j] == nums[j - 1]) {
                continue;
            }
            int s = j + 1, t = nums.size() - 1, curTarget = target -(nums[i] + nums[j]);
            while (s < t) {
                //cout<<nums[s]<<nums[t]<<target<<endl;
                if (nums[s] + nums[t] < curTarget) {
                    s++;
                } else if (nums[s] + nums[t] > curTarget) {
                    t--;
                } else {
                    ret.push_back({nums[i], nums[j], nums[s], nums[t]});
                    while (s < t && nums[s] == nums[s + 1]) {
                        s++;
                    }
                    while (t > s && nums[t] == nums[t - 1]) {
                        t--;
                    }
                    s++;
                    t--;
                }
            }
        }
    }
    return ret;
}

相关文章

  • LeetCode #18 2018-07-28

    18. 4Sum Given an array nums of n integers and an integer...

  • 力扣每日一题:18.四数之和

    18.四数之和 https://leetcode-cn.com/problems/4sum/[https://le...

  • 18.四数之和

    18.四数之和 题目链接:https://leetcode-cn.com/problems/4sum/[https...

  • leetcode 18. 4Sum

    leetcode 18. 4Sum 题目,但是其解题思路可以延伸到 ksum 参考:1 ksum

  • 18. 4Sum

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum

    Description Given an array S of n integers, are there ele...

  • 18. 4Sum

    在3Sum基础上,固定第一个数对剩下的数进行3Sum计算,复杂度为O(n^3)

  • 18. 4Sum

    题目描述:给定一个有n个整数的数组S和目标值target,找到其中所有由四个数a、b、c、d组成,使得a + b ...

  • 18. 4Sum

    题目 Given an array S of n integers, are there elements a, ...

网友评论

      本文标题:18. 4Sum

      本文链接:https://www.haomeiwen.com/subject/xokjhftx.html