LeetCode-15 3Sum(求3数和为零的情况总数)
来源:互联网 发布:软件管理下载安装 编辑:程序博客网 时间:2024/06/05 15:40
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
思路:等同于求两个数和的相反数是否存在于这个数组中。可以延伸到K sum的问题。
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(num); int start = 0; while (start < num.length-2) { if (start == 0 || num[start] != num[start-1] ) { //留意判断条件,之前写的是start与start+1不等,导致一直不对。。 int instart = start+1; int inlast = num.length-1; while (instart < inlast) {if (num[instart] + num[inlast] == -num[start]) {//这里可以考虑用二分法查找来优化。List<Integer> temp = new ArrayList<Integer>();temp.add(num[start]);temp.add(num[instart]);temp.add(num[inlast]);list.add(temp);do {inlast--;//重复的数在这里直接跳过。} while (num[inlast] == num[inlast+1] && instart < inlast);do{instart++;} while(num[instart] == num[instart-1] && instart < inlast);}else if (num[instart] + num[inlast] > -num[start]) {inlast--;}else {instart++;}} } start++;} return list; }}
Runtime: 358 ms
更多收获可参考(个人觉得很棒):Summary for LeetCode 2Sum, 3Sum, 4Sum, K Sum
0 0
- LeetCode-15 3Sum(求3数和为零的情况总数)
- LeetCode 3Sum 三个数和为零的集合 C++完整程序
- 求一组数中的的和为给定值的三个数(3sum)
- LeetCode | 15. 3Sum(三数和为定值)
- 数据结构与算法[LeetCode]—3Sum 求数组中和为0 的三个数的组合
- 3Sum(数组中三个数之和为零)
- leetcode_15. 3Sum-求数组中三个数和为0
- LeetCode | 3Sum(三个数的和等于0)
- LeetCode OJ 之 3Sum (三个数的和)
- 【USACO题库】2.3.3 Zero Sum和为零
- 【USACO题库】2.3.3 Zero Sum和为零
- JZOJ1268.【USACO题库】2.3.3 Zero Sum和为零
- 1031. 【USACO题库】2.3.3 Zero Sum和为零
- leetcode 113. Path Sum II 二叉树求符合和值为sum的链
- 【Leetcode 15】3Sum 三数和问题 C++
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 求数组内任意三个数相加和为零的组合
- 3Sum 数组找3数之和为0 @LeetCode
- 黄斤德:综述美国经济局部疲软、总体依旧热似朝阳
- 【学习ARToolkit小记之二】 videoTest.exe/simpleTest.exe运行出错停止的解决方法
- windows下androidNDK环境配置
- c++计时器
- C++常用的预处理指令:
- LeetCode-15 3Sum(求3数和为零的情况总数)
- android setVisibility三种状态值的解释
- leetcode-15 3Sum
- leetcode第88题-Merge Sorted Array
- rtcm 报文
- 哈希算法学习
- Mac技巧
- Linux下端口被占用解决
- 以MyBatis+SpringMVC3.0实现的,借鉴了Hibernate设计思想,采用封装、抽象、继承的设计思想,做到了数据与相应的操作的高内聚低耦合的实现