4Sum

Posted by Bill on March 27, 2023

18. 4Sum

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.


Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

C++ Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
 public:
  struct VectorHash {
      size_t operator()(const std::vector<int>& v) const {
          std::hash<int> hasher;
          size_t seed = 0;
          for (int i : v) {
              seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
          }
          return seed;
      }
  };
  using MySet = std::unordered_set<std::vector<int>, VectorHash>;
  
  vector<vector<int>> fourSum(vector<int>& nums, int target) {
    vector<vector<int>> ret;
    MySet my_set;
    int len = nums.size();
    sort(nums.begin(), nums.end());
    for (int i = 0; i < len;i++) {
      long long second_target = target - nums[i];
      for (int j = i + 1;j < len;j++) {
          long long third_target = second_target - nums[j];
          int left = j + 1;
          int right = len - 1;
          while (left < right) {
            if (third_target == nums[left] + nums[right]) {
              auto tmp = vector<int>{nums[i],nums[j],nums[left],nums[right]};
              if (my_set.count(tmp) == 0){
                ret.push_back(tmp);
                my_set.insert(tmp);
              }
              left++;
            } else if (third_target > nums[left] + nums[right]) {
              left++;
            } else {
              right--;
            }
          }
      }
    }
    return ret;
  }
 };