描述
题意:给定一个包含 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] ]
链接
18. 四数之和 - 力扣(LeetCode) (leetcode-cn.com)
解法
需要非常注意 先后顺序。
注意区别于 三数之和 ,由于 target不一定取0,比如当 target为-11时,[1,-2,-5,-4,-3,3,3,5],仍然是有解的。
1 class Solution { 2 public List<List<Integer>> fourSum(int[] nums, int target) { 3 List<List<Integer>> res = new ArrayList<>(); 4 if(nums.length < 4) return res; 5 6 Arrays.sort(nums); 7 8 for(int i = 0; i < nums.length; i++) { 9 // if(nums[i] > target) return res; // 当 -11的时候,[1,-2,-5,-4,-3,3,3,5],不能正常计算 10 11 if( i > 0 && nums[i]== nums[i-1]) { 12 continue; 13 } 14 for(int j = i+1; j < nums.length; j++) { 15 if(j > i+1 && nums[j] == nums[j-1]) { 16 continue; 17 } 18 int left = j + 1; 19 int right = nums.length - 1; 20 while(left < right) { 21 int sum = nums[i] + nums[j] + nums[left] + nums[right]; 22 if(sum == target) { 23 res.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[j], nums[left], nums[right]))); 24 left++; 25 right--; 26 while (left < right && nums[left] == nums[left - 1]) { 27 left++; 28 } 29 while (left < right && nums[right] == nums[right + 1]) { 30 right--; 31 } 32 33 } 34 else if(sum > target) { 35 right--; 36 } 37 else{ 38 left++; 39 } 40 41 } 42 } 43 } 44 return res; 45 } 46 }
同时需要注意
以及
之间的区别。
left++;
right--;
的位置关系到 while循环判断的内容的不同。
具体为 left++;right-- 关系到 是 当前值 还是 已经过渡到 下一个值。
left++;right-- 在前,那么 已经过度到 下一个值,那么 判断时,应当 下一个值 nums[left] 与 当前值 nums[left - 1] 做比较;同理,下一个值nums[right] 与当前值 nums[left]做比较。
left++;right-- 在后,则刚好相反。
题解链接