4Sum

描述

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≤da \leq b \leq c \leq da≤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. (-1, 0, 0, 1)
  2. (-2, -1, 1, 2)
  3. (-2, 0, 0, 2)

分析

先排序,然后左右夹逼,复杂度 O(n3)O(n^3),会超时。

可以用一个hashmap先缓存两个数的和,最终复杂度O(n3)O(n^3)。这个策略也适用于 3Sum 。

左右夹逼

  1. // 4Sum
  2. // 先排序,然后左右夹逼
  3. // Time Complexity: O(n^3),Space Complexity: O(1)
  4. class Solution {
  5. public:
  6. vector<vector<int>> fourSum(vector<int>& nums, int target) {
  7. vector<vector<int>> result;
  8. if (nums.size() < 4) return result;
  9. sort(nums.begin(), nums.end());
  10. for (int i = 0; i < nums.size() - 3; ++i) {
  11. if (i > 0 && nums[i] == nums[i-1]) continue;
  12. for (int j = i + 1; j < nums.size() - 2; ++j) {
  13. if (j > i+1 && nums[j] == nums[j-1]) continue;
  14. int k = j + 1;
  15. int l = nums.size() - 1;
  16. while (k < l) {
  17. const int sum = nums[i] + nums[j] + nums[k] + nums[l];
  18. if (sum < target) {
  19. ++k;
  20. while(nums[k] == nums[k-1] && k < l) ++k;
  21. } else if (sum > target) {
  22. --l;
  23. while(nums[l] == nums[l+1] && k < l) --l;
  24. } else {
  25. result.push_back({nums[i], nums[j], nums[k], nums[l]});
  26. ++k;
  27. --l;
  28. while(nums[k] == nums[k-1] && k < l) ++k;
  29. while(nums[l] == nums[l+1] && k < l) --l;
  30. }
  31. }
  32. }
  33. }
  34. return result;
  35. }
  36. };

HashMap 做缓存

  1. // 4Sum
  2. // 用一个hashmap先缓存两个数的和
  3. // Time Complexity: 平均O(n^2),最坏O(n^4),Space Complexity: O(n^2)
  4. class Solution {
  5. public:
  6. vector<vector<int> > fourSum(vector<int> &nums, int target) {
  7. vector<vector<int>> result;
  8. if (nums.size() < 4) return result;
  9. sort(nums.begin(), nums.end());
  10. unordered_map<int, vector<pair<int, int> > > cache;
  11. for (size_t a = 0; a < nums.size(); ++a) {
  12. for (size_t b = a + 1; b < nums.size(); ++b) {
  13. cache[nums[a] + nums[b]].push_back(pair<int, int>(a, b));
  14. }
  15. }
  16. for (int c = 0; c < nums.size(); ++c) {
  17. for (size_t d = c + 1; d < nums.size(); ++d) {
  18. const int key = target - nums[c] - nums[d];
  19. if (cache.find(key) == cache.end()) continue;
  20. const auto& vec = cache[key];
  21. for (size_t k = 0; k < vec.size(); ++k) {
  22. if (c <= vec[k].second)
  23. continue; // 有重叠
  24. result.push_back( { nums[vec[k].first],
  25. nums[vec[k].second], nums[c], nums[d] });
  26. }
  27. }
  28. }
  29. sort(result.begin(), result.end());
  30. result.erase(unique(result.begin(), result.end()), result.end());
  31. return result;
  32. }
  33. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/array/4sum.html