15. 3Sum
来源:互联网 发布:电信机顶盒网络连接 编辑:程序博客网 时间:2024/06/02 05:10
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.
public class Solution {public List<List<Integer>> threeSum(int[] nums) {Arrays.sort(nums);//sort进行排序List<List<Integer>> list = new ArrayList<List<Integer>>();for(int i = 0; i < nums.length-2; i++) {if(i > 0 && (nums[i] == nums[i-1]))continue;//避免重复for(int j = i+1, k = nums.length-1; j < k;) {int sum = nums[i] + nums[j] + nums[k];if(sum == 0) {list.add(Arrays.asList(nums[i],nums[j],nums[k]));j++;k--;while((j < k) && (nums[j] == nums[j-1]))j++;//避免重复while((j < k) && (nums[k] == nums[k+1]))k--;//避免重复}else if (sum > 0)k--;//结果大于0,大数往里缩elsej++;//结果小于0,小数往里缩}}return list;}}//大致思路就是先排序,然后第一个数从0到num.length-2遍历,后面俩数初始放在最前面和最后面,然后慢慢的向里面靠近。此算法打败了92.68%的人。
//发现很多算法题都是两边入手往里,或者找到中间值向外扩。
0 0
- 15. 3Sum && 16 sum closet && 18 4sum
- 15. 3Sum 和 18. 4Sum
- 1. Two Sum&15. 3Sum
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- 15. 3Sum
- [leetcode] 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- leetcode 15. 3Sum
- SQL注入
- [算法最优]设计一个有getMin功能的栈
- const与define之间的区别?
- 使用pull解析xml文件
- 第七周项目二 利用友元类进行对时间与日期的修改
- 15. 3Sum
- css中的层叠顺序和选择器
- whu1608 遍历子集状压写法
- ajax全接触
- java 封装
- java io (java输入输出流)详解
- JAVA对象比较器Comparator
- LeetCode *** 257. Binary Tree Paths
- Android 无线调试