18 4Sum

18. 4Sum

1. Question

Given an arraySofnintegers, are there elementsa,b,c, anddinSsuch thata+b+c+d= target? Find all unique quadruplets in the array which gives the sum of target.

Note: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]
]

2. Implementation

(1) Two Pointers

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();

        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i - 1] == nums[i]) continue;

            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j > i + 1 && nums[j - 1] == nums[j]) continue;

                int k = j + 1, m = nums.length - 1;

                while (k < m) {
                    int sum = nums[i] + nums[j] + nums[k] + nums[m];

                    if (sum == target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[k], nums[m]));
                        ++k;
                        --m;

                        while (k < m && nums[k - 1] == nums[k]) ++k;
                        while (k < m && nums[m] == nums[m + 1]) --m;
                    }
                    else if (sum < target) {
                        ++k;
                    }
                    else {
                        --m;
                    }
                }
            }
        }
        return res;
    }
}

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n^3)

Last updated