leetcode 18 4Sum

Posted GadyPu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 18 4Sum相关的知识,希望对你有一定的参考价值。

题目连接

https://leetcode.com/problems/4sum/  

4Sum

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

二分查找,先预先枚举出$a + b$所得的$n^2$个数字并排好序。
然后判断是否有$a+b=target-c-d$(二分查找即可)
PS:注意所求的四个数下标各不相同,枚举的时候要加以判断
PPS:所得结果可能需要去重。

class Solution {
    using vec = vector<int>;
    using mat = vector<vec>;
    using pii = pair<int, pair<int, int>>;
public:
    mat fourSum(vec& nums, int target) {
        mat res;
        int n = 0;
        if(!(n = nums.size()) || n < 4) return res;
        vector<pii> vpi;
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                vpi.push_back({ nums[i] + nums[j], { i, j } });
            }
        }
        sort(vpi.begin(), vpi.end(), [](pii &a, pii &b)->bool {
            return a.first < b.first;
        });
        int size = vpi.size();
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                int lb = 0, ub = size - 1;
                int k = target - nums[i] - nums[j];
                while(lb <= ub) {
                    int m = (lb + ub) >> 1;
                    if(vpi[m].first >= k) ub = m - 1;
                    else lb = m + 1;
                }
                while(lb < size && vpi[lb].first == k) {
                    auto &r = vpi[lb++].second;
                    if(r.first == i || r.first == j || r.second == i || r.second == j) continue;
                    int a = nums[i], b = nums[j], c = nums[r.first], d = nums[r.second];
                    if(a + b + c + d != target) continue;
                    if (a > b) swap(a, b);
                    if (c > d) swap(c, d);
                    if (a > c) swap(a, c);
                    if (b > d) swap(b, d);
                    if (b > c) swap(b, c);
                    res.push_back({ a, b, c, d });
                }
            }
        }
        sort(res.begin(), res.end());
        res.erase(unique(res.begin(), res.end()), res.end());
        return res;
    }
};

以上是关于leetcode 18 4Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode——18. 4Sum

[leetcode-18-4Sum]

LeetCode 18. 4Sum

LeetCode:18. 4Sum(Medium)

[LeetCode] 18. 4Sum

Leetcode18 4Sum