Leetcode015 3Sum
2016-03-10 22:34
260 查看
public class S015 { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> result = new ArrayList<List<Integer>>(); for(int i =0;i<nums.length;i++){ if(i>0&&nums[i]==nums[i-1]){ continue;//重复的直接跳过 } int left = i+1;//从i+1开始也是防止重复的办法 int right = nums.length-1; while(left<right){ if(nums[left]+nums[right] == -nums[i]){ List<Integer> temp = new ArrayList<Integer>();//必须每次新建 temp.add(nums[i]); temp.add(nums[left]); temp.add(nums[right]); Collections.sort(temp); result.add(temp); //特别注意下面两个while循环 left++; right--;//防止重复 while(left<right&&nums[left]==nums[left-1]){ left++;//防止重复 } while(left<right&&nums[right]==nums[right+1]){ right--;//防止重复 } //这两个条件特别重要,思考一下为何分别是left++和right--; }else if(nums[left]+nums[right] < -nums[i]){ left++; }else{ right--; } } } return result; } }
相关文章推荐
- lambda语句与匿名函数
- BZOJ 1260: [CQOI2007]涂色paint 区间DP
- 关于printf输出格式类型的总结
- CentOS6.5安装NVIDIA的显卡驱动
- Redhat下 Boost库1.54编译安装
- 阻塞,非阻塞connect()和accept()
- COCOS学习笔记--Menu菜单系统
- mongodb重启失败ERROR: child process failed, exited with error number 1
- PAGELATCH_EX Contention on 2:1:103
- 泛型,链表
- postgresql 触发器
- linux中的特殊字符含义
- U盘安装Windows和Ubuntu 15.04双系统图解教程
- 软件测试 fault error和failure
- [LeetCode]题解(python):115-Distinct Subsequences
- POJ 1066 Treasure Hunt [想法题]
- 程序员练级之路 (作者:陈皓)
- 兔子的烦恼(一)
- 关于java的类
- Catalog与Schema