[Lintcode]3Sum
来源:互联网 发布:神硕微信免费推广软件 编辑:程序博客网 时间:2024/04/30 05:30
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.
这道题貌似没有什么简单算法,所以直接三重循环,三个指针,遍历所有可能性。记得提前排序和pass掉重复元素。
public class Solution { /** * @param numbers : Give an array numbers of n integer * @return : Find all unique triplets in the array which gives the sum of zero. */ public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) { Arrays.sort(numbers); ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); for(int right = numbers.length - 1; right > 1; right--) { for(int left = 0; left < right - 1; left++) { for(int i = left + 1; i < right; i++) { if(numbers[left] + numbers[right] + numbers[i] == 0) { ArrayList<Integer> tmp = new ArrayList<Integer>(); tmp.add(numbers[left]); tmp.add(numbers[i]); tmp.add(numbers[right]); res.add(tmp); break; } } while(left + 1 < right && numbers[left] == numbers[left + 1]) left++; } while(right - 1 > 0 && numbers[right] == numbers[right - 1]) right--; } return res; }}
0 0
- lintcode:3 Sum Closest
- lintcode:3 Sum
- [Lintcode]3Sum
- Lintcode - k sum II
- [LintCode]k Sum
- [LintCode]k Sum II
- 2 Sum-LintCode
- lintcode:Continuous Subarray Sum
- lintcode Interval Sum
- lintcode:2sum
- lintcode:Subarray Sum Closest
- [LintCode]Submatrix Sum
- [LintCode] Continuous Subarray Sum
- [Lintcode]Minimum Path Sum
- lintcode: Subarray Sum Closest
- lintcode:k Sum II
- lintcode:Combination Sum
- *[Lintcode] Subarray Sum
- Xcode 7.2 真机测试 iOS9.3 系统
- IO中同步、异步与阻塞、非阻塞的区别
- Android 常用抓包工具介绍之Charles
- 七、2440裸机开发 触摸屏操作
- 订单捕获-销售订单工作台
- [Lintcode]3Sum
- Android SQLite 升级数据库,在原有数据库的基础上添加一列
- leetcode-338. Counting Bits
- 第一章 JAVA入门(javad的平台无关性)
- oracle 分析函数应用
- Java继承机制的初始化顺序+静态动态绑定
- 八、责任链设计模式
- 练习三 1016
- Swift初始化方法顺序