18 4 Sum

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 pointer,O(n^3)

public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
    ArrayList<ArrayList<Integer>> res = new ArrayList<>();
    if (numbers == null || numbers.length == 0) {
        return res;
    }

    Arrays.sort(numbers);

    int len = numbers.length;
    for (int i = 0; i < len - 3; i++) {
        if (i != 0 && numbers[i] == numbers[i - 1]) { // remove dup
            continue;
        }

        for (int j = i + 1; j < len - 2; j++) {
            if (j != i + 1 && numbers[j] == numbers[j - 1]) { // remove dup
                continue;
            }

            int left = j + 1;
            int right = len - 1;
            while (left < right) {
                int sum = numbers[i] + numbers[j] + numbers[left] + numbers[right];
                if (sum == target) {
                    ArrayList<Integer> tmp = new ArrayList<>();
                    tmp.add(numbers[i]);
                    tmp.add(numbers[j]);
                    tmp.add(numbers[left]);
                    tmp.add(numbers[right]);
                    res.add(tmp);
                    left++;
                    right--;

                    // remove dup
                    while (left < right && numbers[left] == numbers[left - 1]) {
                        left++;
                    }
                    // remove dup
                    while (left < right && numbers[right] == numbers[right + 1]) {
                        right--;
                    }

                } else if (sum > target) {
                    right--;
                } else {
                    left++;
                }
            }
        }
    }
    return res;
}

Last updated