18. 四数之和
难度中等592
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]思路很简单:排序,固定两个数,然后双指针
但是一到了去重,就开始拉低命中率
import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Solution { // 原始做法是O(n^4) // 可以通过排序,然后选定一个数,转化为三数之和,然后再选定一个数,用双指针? 变成O(n^3) public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> rs = new ArrayList<>(); if (nums.length < 4) { return rs; } Arrays.sort(nums); boolean found = false; for (int i = 0; i < nums.length - 3; i++) { if (found && nums[i] == nums[i - 1]) { continue; } found = false; for (int j = i + 1; j < nums.length - 2; j++) { if (found && nums[j] == nums[j - 1]) { continue; } int lo = j + 1, hi = nums.length - 1; while (lo < hi) { int t = nums[i] + nums[j] + nums[lo] + nums[hi]; if (t > target) { hi--; } else if (t < target) { lo++; } else { rs.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi])); lo++; hi--; while (lo < nums.length && nums[lo] == nums[lo - 1]) { lo++; } while (hi >= 0 && nums[hi] == nums[hi + 1]) { hi--; } found = true; } } } } return rs; } public static void main(String[] args) { int[] a = {-1, -5, -5, -3, 2, 5, 0, 4}; new Solution().fourSum(a, -7); } }我这里的去重好像写复杂了:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Solution { // 原始做法是O(n^4) // 可以通过排序,然后选定一个数,转化为三数之和,然后再选定一个数,用双指针? 变成O(n^3) public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> rs = new ArrayList<>(); if (nums.length < 4) { return rs; } Arrays.sort(nums); for (int i = 0; i < nums.length - 3; i++) { if(i>0&&nums[i]==nums[i-1]){ continue; } for (int j = i + 1; j < nums.length - 2; j++) { // 注意,不要让j和i对比,j-1必须大于i // 永远只是根本轮的上一个对比 if ((j-1)>i && nums[j] == nums[j - 1]) { continue; } int lo = j + 1, hi = nums.length - 1; while (lo < hi) { int t = nums[i] + nums[j] + nums[lo] + nums[hi]; if (t > target) { hi--; } else if (t < target) { lo++; } else { rs.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi])); lo++; hi--; while (lo < nums.length && nums[lo] == nums[lo - 1]) { lo++; } while (hi >= 0 && nums[hi] == nums[hi + 1]) { hi--; } } } } } return rs; } public static void main(String[] args) { int[] a = {-1, 0, 1, 2, -1, -4}; new Solution().fourSum(a, -1); } }