首页 > 其他 > 详细

【Leetcode】4Sum

时间:2014-03-18 12:07:33      阅读:410      评论:0      收藏:0      [点我收藏+]

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)
bubuko.com,布布扣
 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的写法好别扭...

【Leetcode】4Sum,布布扣,bubuko.com

【Leetcode】4Sum

原文:http://www.cnblogs.com/dengeven/p/3606355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!