15,3Sum
来源:互联网 发布:windows 自带工具 u盘 编辑:程序博客网 时间:2024/05/17 08:00
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.//给一个整形数组,找出三个数a、b、c,找出不重复的集合,满足加起来为0,注意a<=b<=c;
题目分析:
该题解法为,先对数组进行排序,然后以一个为基准,对后面的元素进行双指针查找,示例
[-1,0,1,2,-1,-4]
第一轮:以第一位为准,后面的元素,使用双指针,使之满足一定条件
代码如下:
public class Solution { public List<List<Integer>> threeSum(int[] num) { //1,判断输入出错的状况 if(num==null||num.length<3) return new ArrayList<List<Integer>>(); //2,排序 Arrays.sort(num); //3,处理 List<List<Integer>> result_list=new ArrayList<List<Integer>>(); for(int i=0;i<num.length-2;++i) { int index1=i+1,index2=num.length-1; int twoSum=-num[i]; while(index1<index2) { if(num[index1]+num[index2]<twoSum) index1++; else if (num[index1]+num[index2]>twoSum) index2--; else {List<Integer> list=new ArrayList<Integer>();list.add(num[i]);list.add(num[index1]);list.add(num[index2]);result_list.add(list);while(index1<index2&&num[index1]==num[index1+1])index1++;while(index1<index2&&num[index2]==num[index2-1])index2--;index1++;index2--;} } //注意0000这种状况 while(i<num.length-2&&num[i+1]==num[i]) i++; } return result_list; }}
0 0
- [Leetcode] #1#15#18 2Sum & 3Sum & 4Sum
- Sum—LeetCode-15 3Sum
- leetcode 15 3 sum 4 sum
- Leetcode 15 3Sum
- LeetCode 15: 3Sum
- leetcode 15 3Sum
- [leetcode 15] 3Sum
- Leetcode【15】:3Sum
- [leetcode 15] 3Sum
- [Leetcode] 15 - 3Sum
- leetcode.15-----------3Sum
- 15,3Sum
- leetcode 15 3Sum
- leetcode-15 3Sum
- 3Sum - LeetCode 15
- Leetcode #15 3 Sum
- LeetCode---(15) 3 sum
- LeetCode 15 - 3Sum
- Pretty Poem(substr)
- Linux下Java路径问题/Javac java -cp
- Android项目中引用外部项目library失败的原因
- Castle学习系列(十二)---Windsor和DynamicProxy实现AOP
- 快速排序的随机化算法
- 15,3Sum
- Android案例之新闻客户端服务器实现,完全属于自己的新闻展示平台
- 感想
- OC中面向对象语法类与对象
- ddpush 学习之路 2 DateTimeUtil.java
- MySQL服务器连接过程分析
- 同步与异步
- C++标准转换运算符const_cast
- 买房子