四数之和

题目描述:给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:双指针法

首先,将nums排序;然后first和fourth指针分别从数组的第一个和最后一位开始,second和third指针分别从first+1和fourth-1处从两边向内移动,直到second不小于third,移动过程中需要判断4个指针所指向的数字之和是否和target相等,如果相等,则放到结果集result里面。 直到遍历到first不小于fourth-2为止,最后返回结果result。

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. public class Solution {
  5. public static List<List<Integer>> fourSum(int[] nums, int target) {
  6. if (nums == null || nums.length < 4) {
  7. return new ArrayList<>();
  8. }
  9. if (nums.length == 4 && nums[0] + nums[1] + nums[2] + nums[3] != target) {
  10. return new ArrayList<>();
  11. }
  12. Arrays.sort(nums);
  13. List<List<Integer>> result = new ArrayList<>();
  14. for (int first = 0, fourth = nums.length - 1; first < fourth - 2; first++) {
  15. // 过滤掉重复的
  16. if (first > 0 && nums[first] == nums[first - 1]) {
  17. continue;
  18. }
  19. while (first < fourth - 2) {
  20. // 过滤掉重复的
  21. if (fourth < nums.length - 1 && nums[fourth] == nums[fourth + 1]) {
  22. fourth--;
  23. continue;
  24. }
  25. for (int second = first + 1, third = fourth - 1; second < third; second++) {
  26. // 过滤掉重复的
  27. if (second > first + 1 && nums[second] == nums[second - 1]) {
  28. continue;
  29. }
  30. while (second < third && nums[first] + nums[second] + nums[third] + nums[fourth] > target) {
  31. third--;
  32. }
  33. if (second != third && nums[first] + nums[second] + nums[third] + nums[fourth] == target) {
  34. result.add(new ArrayList<>(Arrays.asList(new Integer[]{nums[first], nums[second], nums[third], nums[fourth]})));
  35. }
  36. }
  37. fourth--;
  38. }
  39. fourth = nums.length - 1;
  40. }
  41. return result;
  42. }
  43. public static void main(String[] args) {
  44. int[] nums = new int[]{-3, -1, 0, 2, 4, 5};
  45. for (List<Integer> integers : fourSum(nums, 0)) {
  46. for (Integer integer : integers) {
  47. System.out.print(integer + "/");
  48. }
  49. System.out.println();
  50. }
  51. }
  52. }

【每日寄语】忠实的守住自己最初的梦想,让生活的每一天都变得有意义。