• 18. 4Sum


    Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note: The solution set must not contain duplicate quadruplets.

    For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
    
    A solution set is:
    [
      [-1,  0, 0, 1],
      [-2, -1, 1, 2],
      [-2,  0, 0, 2]
    ]
    题目含义:从数组中找4个数字,使得加和等于目标值target,找出所有的组合

     1   public List<List<Integer>> threeSum(int[] nums, int target, int firstNumber) {
     2         List<List<Integer>> res = new LinkedList<>();
     3         for (int i = 0; i < nums.length; i++) {
     4             if (i > 0 && nums[i] == nums[i - 1]) continue;
     5             int low = i + 1, high = nums.length - 1;
     6             while (low < high) {
     7                 if (nums[i] + nums[low] + nums[high] == target) {
     8                     res.add(Arrays.asList(firstNumber, nums[i], nums[low], nums[high]));
     9                     while (low < high && nums[low] == nums[low + 1]) low++;
    10                     while (low < high && nums[high] == nums[high - 1]) high--;
    11                     low++;
    12                     high--;
    13                 } else if (nums[i] + nums[low] + nums[high] > target) high--;
    14                 else low++;
    15             }
    16         }
    17         return res;
    18     }
    20 
    21     public List<List<Integer>> fourSum(int[] nums, int target) {
    22         Arrays.sort(nums);
    23         List<List<Integer>> res = new LinkedList<>();
    24         if (nums.length == 0) return res;
    25         for (int i = 0; i < nums.length; i++) {
    26             if (i > 0 && nums[i] == nums[i - 1]) continue;
    27             int[] rightNums = Arrays.copyOfRange(nums, i+1, nums.length);
    28             List<List<Integer>> threeSum = threeSum(rightNums, target - nums[i], nums[i]);
    29             res.addAll(threeSum);
    30         }
    31         return res;
    32     }

     类似题目:15. 3Sum

  • 相关阅读:
    转:浅谈深度学习(Deep Learning)的基本思想和方法
    随记:我们需要怎样的数学教育?
    转 :hlda文献学习笔记
    转:关于Latent Dirichlet Allocation及Hierarchical LDA模型的必读文章和相关代码
    推荐算法相关总结表(包括DM)
    转 自己动手写推荐系统
    求熵 python 代码
    特征值与特征向量
    转: 谱聚类
    链接数据库
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7732097.html
Copyright © 2020-2023  润新知