LeetCode 18. 4 Sum

Time:2020-3-23

Title Description (medium difficulty)

LeetCode 18. 4 Sum

Similar to 3sum, it’s just to find four numbers so that the sum is target and there can’t be duplicate sequences.

If you haven’t done 3sum before, you can take a look at it first. You just added a cycle on the basis of the above.

public List<List<Integer>> fourSum(int[] num, int target) {
    Arrays.sort(num);
    List<List<Integer>> res = new LinkedList<>();
    //Added layer cycle
    for (int j = 0; j < num.length - 3; j++) {
        //Prevent duplicate
        if (j == 0 || (j > 0 && num[j] != num[j - 1]))
            for (int i = j + 1; i < num.length - 2; i++) {
                //Prevent duplicate,不再是 i == 0 ,因为 i 从 j + 1 开始
                if (i == j + 1 || num[i] != num[i - 1]) {
                    int lo = i + 1, hi = num.length - 1, sum = target - num[j] - num[i];
                    while (lo < hi) {
                        if (num[lo] + num[hi] == sum) {
                            res.add(Arrays.asList(num[j], num[i], num[lo], num[hi]));
                            while (lo < hi && num[lo] == num[lo + 1])
                                lo++;
                            while (lo < hi && num[hi] == num[hi - 1])
                                hi--;
                            lo++;
                            hi--;
                        } else if (num[lo] + num[hi] < sum)
                            lo++;
                        else
                            hi--;
                    }
                }
            }
    }
    return res;
}

Time complexity: O (n? 3).

Spatial complexity: O (n), in the worst case, n refers to the number of permutations and combinations of n elements, that is, $$n = C ^ 4 $$, which is used to save the results.

total

It’s completely written according to the idea of 3sum, which is easy to understand.

See leetcode.wang for more details.