18. 4Sum (Medium)

https://leetcode.com/problems/4sum/

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + 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.

Example:

Given array nums = [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]
]

Solutions

class Solution {

    // Similar to 3 sum, just add another outer loop

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

        if (nums.length < 4) {
            return ans;
        }

        Arrays.sort(nums);

        for (int i = 0; i <= nums.length - 4; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) {
                continue; // avoid duplicates
            }

            for (int j = i + 1; j <= nums.length - 3; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) {
                    continue; // avoid duplicates
                }

                int x = j + 1;
                int y = nums.length - 1;

                while (x < y) {
                    if (x != j + 1 && nums[x] == nums[x - 1]) { // avoid duplicates
                        x++;
                        continue;
                    }

                    if (y != nums.length - 1 && nums[y] == nums[y + 1]) { // avoid duplicates
                        y--;
                        continue;
                    }

                    int sum = nums[i] + nums[j] + nums[x] + nums[y];

                    if (sum < target) {
                        x++;
                    }

                    if (sum > target) {
                        y--;
                    }

                    if (sum == target) {
                        ans.add(Arrays.asList(nums[i], nums[j], nums[x++], nums[y--]));
                    }
                }
            }
        }

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-02-26 11:13:24

results matching ""

    No results matching ""