zoukankan      html  css  js  c++  java
  • 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)

    这个方法不会!

  • 相关阅读:
    ASP.NET2.0中将文件上传到数据库
    C#中数据类型转换
    数据绑定以及Container.DataItem的具体分析
    CodeSmith开发系列资料总结
    Jquery信息专题收集
    microsoft .net framework专题汇总
    ASP.NET中插入FLASH代码
    javascript专题汇总
    经典SQL行列转换
    前台js调用后台c#方法
  • 原文地址:https://www.cnblogs.com/tao-alex/p/6443028.html
Copyright © 2011-2022 走看看