1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import java.util.*;
public class FourSum18 { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> result = new LinkedList<List<Integer>>(); Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; int threeTarget = target - nums[i];
for (int j = i + 1; j < nums.length - 2; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) continue; int twoTarget = threeTarget - nums[j]; int left = j + 1; int right = nums.length - 1; while (left < right) { if (nums[left] + nums[right] == twoTarget) { List<Integer> newList = new LinkedList<Integer>(); newList.add(nums[i]); newList.add(nums[j]); newList.add(nums[left]); newList.add(nums[right]); result.add(newList); while (++left < right && nums[left] == nums[left - 1]) { } while (left < --right && nums[right] == nums[right + 1]) { } } else if (nums[left] + nums[right] < twoTarget) { left++; } else { right--; } } } } return result; }
public static void main(String[] args) { int[] nums = {1, 0, -1, 0, -2, 2}; int[] nums1 = {0, 0, 0, 0}; int[] nums2 = {-3, -2, -1, 0, 0, 1, 2, 3}; int[] nums3 = {-5, -4, -3, -2, -1, 0, 0, 1, 2, 3, 4, 5}; int[] nums4 = {1, -2, -5, -4, -3, 3, 3, 5}; int target = -11; FourSum18 fourSum18 = new FourSum18(); List<List<Integer>> res = fourSum18.fourSum(nums4, target); for (int i = 0; i < res.size(); i++) { System.out.println(); for (int j = 0; j < res.get(i).size(); j++) System.out.println(res.get(i).get(j)); } } }
|