zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    linux下编译安装mysql
    Linux系统信息查看命令(转载)
    python使用memcached
    ./configure 命令使用和参数解析
    linux平台下使用 nginx + spawn-cgi 部署webpy程序
    冒泡排序
    在gitub上添加ssh key
    给p标签做单行省略 设置宽度的问题
    移动端的无缝滚动
    canvas-图片翻转
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7732097.html
Copyright © 2011-2022 走看看