• 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;
        }
    };
  • 相关阅读:
    Python cmd库的简易使用
    声明式编程与命令式编程
    javascript移除树形列表(带children的对象数组)中的元素
    javascript将树结构的列表转换为普通列表(不带children)
    javascript将普通列表转换为树结构的列表(带children)
    webservice的概述
    java程序员面试应该具备的一些基本技能
    mysql生成随机id
    struts2的优点
    javascript常用的正则表达式集合
  • 原文地址:https://www.cnblogs.com/GadyPu/p/5608729.html
Copyright © 2020-2023  润新知