• code第一部分数组:第九题 四个元素之和为给定目标


    code第一部分数组:第九题  四个元素之和为给定目标

    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, a ≤ b ≤ c ≤ d)
    • 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)


    解决方案1 先排序,然后二分查找,复杂度 O(n3 log n)

    vector<vector<int>> fourSum(vector<int>& num, int target)
    {
        vector<vector<int>> result;
        if (num.size() < 4)
            return result;
        sort(num.begin(), num.end());
        auto last = num.end();
        for (auto a = num.begin(); a < prev(last, 3);a = upper_bound(a, prev(last, 3), *a))
        {
            for (auto b = next(a); b < prev(last, 2);b = upper_bound(b, prev(last, 2), *b))
            {
                for (auto c = next(b); c < prev(last);c = upper_bound(c, prev(last), *c))
                {
                    const int d = target - *a - *b - *c;
                    if (binary_search(next(c), last, d))
                    result.push_back(vector<int> { *a, *b, *c, d });
                }
            }
        }
        return result;
    }

    方法2 使用map做缓存,先缓存两个数的和,时间复杂度 O(n^3),空间复杂度 O(n^2)

    这个方法不会!

  • 相关阅读:
    操作系统Cosmos hal 层的函数调用思维导图
    软件测试 性能测试报告jmeter性能测试
    进程调度模拟算法
    软件测试 性能测试报告
    论软件的系统测试及其应用
    QTP实验
    论MVC架构设计及其应用
    存储管理动态分区分配及回收算法
    浅谈高并发、高性能、高可用
    实验二白盒测试
  • 原文地址:https://www.cnblogs.com/tao-alex/p/6443028.html
Copyright © 2020-2023  润新知