|
| 1 | +package com.thealgorithms.misc; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +public class UniqueQuadruplets { |
| 8 | + public static List<List<Integer>> fourSum(int[] nums, int target) { |
| 9 | + List<List<Integer>> result = new ArrayList<>(); |
| 10 | + if (nums == null || nums.length < 4) return result; |
| 11 | + |
| 12 | + Arrays.sort(nums); |
| 13 | + |
| 14 | + for (int i = 0; i < nums.length - 3; i++) { |
| 15 | + // Skip duplicate values |
| 16 | + if (i > 0 && nums[i] == nums[i - 1]) continue; |
| 17 | + for (int j = i + 1; j < nums.length - 2; j++) { |
| 18 | + // Skip duplicate values |
| 19 | + if (j > i + 1 && nums[j] == nums[j - 1]) continue; |
| 20 | + |
| 21 | + int left = j + 1, right = nums.length - 1; |
| 22 | + while (left < right) { |
| 23 | + int sum = nums[i] + nums[j] + nums[left] + nums[right]; |
| 24 | + if (sum == target) { |
| 25 | + result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); |
| 26 | + while (left < right && nums[left] == nums[left + 1]) left++; // Skip duplicates |
| 27 | + while (left < right && nums[right] == nums[right - 1]) right--; // Skip duplicates |
| 28 | + left++; |
| 29 | + right--; |
| 30 | + } else if (sum < target) { |
| 31 | + left++; |
| 32 | + } else { |
| 33 | + right--; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + return result; |
| 39 | + } |
| 40 | + |
| 41 | + public static void main(String[] args) { |
| 42 | + int[] arr1 = {1, 0, -1, 0, -2, 2}; |
| 43 | + int target1 = 0; |
| 44 | + System.out.println(fourSum(arr1, target1)); |
| 45 | + |
| 46 | + int[] arr2 = {4, 3, 3, 4, 4, 2, 1, 2, 1, 1}; |
| 47 | + int target2 = 9; |
| 48 | + System.out.println(fourSum(arr2, target2)); |
| 49 | + } |
| 50 | +} |
0 commit comments