zoukankan      html  css  js  c++  java
  • 【Leetcode】4Sum

    Given an array S of n integers, are there elements abc, 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 class Solution {
     2 public:
     3     vector<vector<int>> fourSum(vector<int>& num, int target) {
     4         vector<vector<int>> result;
     5         if (num.size() < 4) return result;
     6         sort(num.begin(), num.end());
     7         auto last = num.end();
     8         for (auto a = num.begin(); a < prev(last, 3); ++a) {
     9             if (a != num.begin() && *a == *prev(a)) continue;
    10             for (auto b = next(a); b < prev(last, 2); ++b) {
    11                 if (b != next(a) && *b == *prev(b)) continue;
    12                 auto c = next(b);
    13                 auto d = prev(last);
    14                 while (c < d) {
    15                     int sum = *a + *b + *c + *d;
    16                     if (sum < target) {
    17                         ++c;
    18                     } else if (sum > target) {
    19                         --d;
    20                     } else {
    21                         result.push_back({*a, *b, *c, *d});
    22                         ++c, --d;
    23                     }
    24                 }
    25             }
    26         }
    27         result.erase(unique(result.begin(), result.end()), result.end());
    28         return result;
    29     }
    30 };
    View Code

    与前面的题类似,先排序再夹逼,但是需要循环两次。O(n3).

    其它的方法:hash_map缓存两两元素的和。

    C++11的写法好别扭...

  • 相关阅读:
    归并排序
    快速排序
    UNION与UNION ALL的区别
    聚集索引和非聚集索引
    设计模式之抽象工厂模式
    list中map 的value值时间排序
    webmvc 拦截器 允许跨域 跨域问题 sessionid不一样
    redis 主从复制 和集群
    maven打包
    bcprov-jdk15on包用于创建CSR(证书请求)
  • 原文地址:https://www.cnblogs.com/dengeven/p/3606355.html
Copyright © 2011-2022 走看看