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

Hints

Solutions

  • Java
class Solution {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> results = new ArrayList<>();
        if (nums.length < 4) return results;

        Arrays.sort(nums);

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

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

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

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

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

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

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

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

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

                        x++;
                        y--;
                    }
                }
            }
        }

        return results;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-04 02:48:02

results matching ""

    No results matching ""