LeetCode 15.三数之和 18.四数之和

    科技2022-08-24  104

    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

    注意:答案中不可以包含重复的三元组。

    示例:

    给定数组 nums = [-1, 0, 1, 2, -1, -4],

    满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]

    解法:其实就是对三重循环暴力用双指针的优化加剪枝,保证组合不重复,首先将数组排序,遍历时如果当前数等于该重循环上一个数,则跳过。 双指针在这道题的用法:因为数组是排好序的,如果我们固定了前两重循环枚举到的元素 a 和 b,那么只有唯一的 c 满足 a+b+c=0。当第二重循环往后枚举一个元素 b’ 时,由于 b’ > b,那么满足 a+b’+c’=0的 c’一定有 c’ <c即 c’ 在数组中一定出现在 c 的左侧。也就是说,我们可以从小到大枚举 b,同时从大到小枚举 c

    import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); Arrays.sort(nums); int len = nums.length; for(int i = 0 ; i < len ; i++){ if(i > 0 && nums[i] == nums[i-1]){ continue; } int three = len - 1; int target = -nums[i]; for(int j = i + 1; j < len ; j++){ if(j > i+1 && nums[j] == nums[j - 1]){ continue; } while(j < three && nums[j] + nums[three] > target){ three--; } if(j == three){ break; } if(nums[j] + nums[three] == target){ List<Integer> list = new ArrayList<>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[three]); ans.add(list); } } } return ans; } }

    四数之和: 道理相同,后两重循环用双指针,只不过剪枝的时候多了一些新的判断

    class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> quadruplets = new ArrayList<List<Integer>>(); if (nums == null || nums.length < 4) { return quadruplets; } Arrays.sort(nums); int length = nums.length; for (int i = 0; i < length - 3; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) { break; } if (nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) { continue; } for (int j = i + 1; j < length - 2; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) { break; } if (nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) { continue; } int left = j + 1, right = length - 1; while (left < right) { int sum = nums[i] + nums[j] + nums[left] + nums[right]; if (sum == target) { quadruplets.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); while (left < right && nums[left] == nums[left + 1]) { left++; } left++; while (left < right && nums[right] == nums[right - 1]) { right--; } right--; } else if (sum < target) { left++; } else { right--; } } } } return quadruplets; } }
    Processed: 0.008, SQL: 9