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
|
public static List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list = new ArrayList<>(); if (null == nums || nums.length < 4) { return list; }
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int threeTarget = target - nums[i]; threeSum(nums[i], threeTarget, i+1, nums, list); } return list; }
public static void threeSum(int firt, int target, int left, int[] nums, List<List<Integer>> list) {
for (int i = left; i < nums.length; i++) { if (i > left && nums[i - 1] == nums[i]) { continue; }
int twoTarget = target -nums[i]; twoSum(firt, nums[i], twoTarget, i + 1, nums.length - 1, nums, list); } }
private static void twoSum(int first, int second, int target, int left, int right, int[] nums, List<List<Integer>> list) { while (left < right) { int tmp = nums[left] + nums[right]; if (tmp == target) { list.add(Arrays.asList(first, second, nums[left], nums[right])); left ++; right --;
while (left < right && nums[left - 1] == nums[left]) { left ++; }
while (left < right && nums[right] == nums[right + 1]) { right --; } } else if (tmp > target) { right --; } else if (tmp < target) { left ++; }
} }
|
近期评论