3Sum
来源:互联网 发布:数据恢复多少钱 编辑:程序博客网 时间:2024/06/06 12:50
题目描述:
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)
这里和前面的Two Sum是一个思路,用两个指针往里靠拢,只是多个n次遍历而已。
必须得到不能重复的值,我这里用了set集合,如果重复检查,继续下一次遍历。
public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> result=new ArrayList<List<Integer>>(); Set<Integer> set =new HashSet<Integer>(); for (int i = 0; i < nums.length; i++) { if(!set.contains(nums[i])){ set.add(nums[i]); int low=i+1,high=nums.length-1; while(low<high){ if(nums[low]+nums[high]==0-nums[i]){ List<Integer> list=new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[low]); list.add(nums[high]); result.add(list); //这段循环条件是比较细节的地方,要注意 while(nums[low]==nums[low+1]&&low+1<high){ low++; continue; } low++; }else if(nums[low]+nums[high]<0-nums[i]){ low++; }else{ high--; } } } } return result;}
0 0
- Two Sum && 3 Sum
- 【Leetcode】3Sum (Sum)
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- leetcode 2 sum 3sum 4sum
- 2Sum 3Sum 4Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 3Sum
- 3SUM
- 3-sum
- 3Sum
- 3Sum
- 3Sum
- 3Sum
- intent调用代码总结
- Linux+Nginx/Apache/Tomcat新增SSL证书,开启https访问教程
- PullToRefreshGridView 带下拉刷新,上拉加载的GridView控件
- apache commons io checkstyle报告(2016-04-21更新)
- [算法]找出单链表中的倒数第k个元素
- 3Sum
- 系统服务无法启动的错误信息查看
- Android studio显示行号
- .net全局定时定期执行某些操作在Global.asax中具体实现
- Merge
- Javascript闭包
- uva11729
- require.js
- PHP命名空间(Namespace)的使用详解