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

posted @   daniel456  阅读(420)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示