LeetCoder 解题报告 3Sum
来源:互联网 发布:永诚网络 编辑:程序博客网 时间:2024/05/22 10:47
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)题意:给定一个数组,找出其中的三个数,使之三个数的和为0,并输出这三个数,按从小到大输出,如果有多组就全部输出。
分析:在 LeetCode 解题报告 Two Sum 这篇文章中介绍了三种方法,此题是这个题的升级版,这个题如果用暴力解决那么将是O(n3)的时间复杂度,如果用HashMap也是不方便,因为数据是可重复的。
接下来就直接看代码
public List<List<Integer>> threeSum(int[] num) { Arrays.sort(num); List<List<Integer>> list = new ArrayList<List<Integer>> (); int first, end, mid; //遍历数组 for(int i = 0; i < num.length-2; i++) { if(i==0 || num[i] > num[i-1]) { first = i; end = num.length - 1; mid = first + 1; if(num[first] > 0 || num[end] < 0) break; while(mid < end) { int sum = num[first] + num[mid] + num[end]; if(sum == 0) { ArrayList<Integer> each = new ArrayList<Integer>(); each.add(num[first]); each.add(num[mid]); each.add(num[end]); if(!list.contains(each)) list.add(each); mid++; end--; while(mid < end && num[end] == num[end-1]) end--; while(mid < end && num[mid] == num[mid+1]) mid ++; } else if(sum < 0) { mid++; } else end--; } } } return list; }
思路其实就很简单了,就是锁定第一个值遍历,剩下的两个的数,按照数组中寻找两个数的和是定值来解决就ok了。
如果按着思路写出的代码提交会有出现超时现象,那么我们就要优化了。
这里面做了很多的优化,比如:if(i==0 || num[i] > num[i-1])这里是防止相同数据输入
while(mid < end && num[end] == num[end-1]) end--; while(mid < end && num[mid] == num[mid+1]) mid ++;这里避免不必要的重复
0 0
- LeetCoder 解题报告 3Sum
- LeetCoder 15. 3Sum
- LeetCoder 16 3Sum Closest
- [LeetCode]3Sum,解题报告
- 【LeetCode】3Sum 解题报告
- LeetCode解题报告--3 Sum
- [LeetCode] 3Sum 解题报告
- 3Sum LeetCode 解题报告
- 【LeetCode】3Sum Closest 解题报告
- LeetCode 解题报告 3Sum Closest
- 3Sum——解题报告
- 3Sum Closest ——解题报告
- LeetCode解题报告--3Sum Closest
- [leetcode] 15. 3Sum 解题报告
- [leetcode] 16. 3Sum Closest 解题报告
- [leetcode] 259. 3Sum Smaller 解题报告
- leetcode(16) 3Sum Closest解题报告
- [Leetcode] 15. 3Sum 解题报告
- Android camera bring up
- esp8266路由模式设置
- Java如何扫描指定package下所有的类
- 动态申请和释放一个二维数组
- 三十四、异常(一)异常抛出、异常捕获、异常传播
- LeetCoder 解题报告 3Sum
- 查找试题--互换函数swap初试
- 快速傅里叶变换算法
- 重新加载 vimrc
- redis集群简易实验
- 任意进制转换算法
- 学术休假期 项目5-读懂共同体
- 快速排序算法
- php全局变量和正则表达式错误解决方案