18. 4Sum
来源:互联网 发布:002型航母 知乎 编辑:程序博客网 时间:2024/06/07 06:07
Given an array S of n integers, are there elements a, b, c, 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]]
在3Sum的基础上,在外层再添加一层循环。
public List<List<Integer>> fourSum(int[] num, int target) { Arrays.sort(num); ArrayList<List<Integer>> ans = new ArrayList<>(); if(num.length == 0 || 4 * num[0] > target || 4 * num[num.length - 1] < target) { return ans; } for(int i = 0; i < num.length - 3; i++) { if(i > 0 && num[i] == num[i - 1]) continue; for(int j = i+1; j < num.length - 2; j++) { if(j > i + 1 && num[j] == num[j-1]) continue; int low = j + 1; int high = num.length - 1; while(low < high) { int sum = num[i] + num[j] + num[low] + num[high]; if(sum == target){ ans.add(Arrays.asList(num[i], num[j], num[low], num[high])); low++; high--; while(low < high && num[low] == num[low-1]) low++; while(low < high && num[high] == num[high+1]) high--; } else if(sum<target) { low++; } else { high--; } } } } return ans; }
阅读全文
0 0
- 15. 3Sum 和 18. 4Sum
- LeetCode --- 18. 4Sum
- [Leetcode] 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum LeetCode
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- Vertx项目随笔
- Java中整型与字符串的互相转化
- 爱测未来性能-Tomcat配置参数性能优化
- (转)如何快速处理线上故障
- android面试题-为什么service里面startActivity抛异常?activity不会
- 18. 4Sum
- 多重背包O(VN)算法——单调队列优化
- windows下使用MinGW+msys编译ffmpeg
- 字符串切割strtok+整行输入+vector存储char*
- C语言直接选择排序
- memcpy 的使用方法即指针的应用
- Spring IOC和AOP 原理彻底搞懂
- 开发文档之Kotlin语言
- 带你解锁蓝牙skill(一)