LeetCode-15 3Sum(求3数和为零的情况总数)
2015-04-22 15:37
323 查看
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.
思路:等同于求两个数和的相反数是否存在于这个数组中。可以延伸到K sum的问题。
Runtime: 358 ms
更多收获可参考([b]个人觉得很棒):[/b]Summary for LeetCode 2Sum, 3Sum,
4Sum, K Sum
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)
思路:等同于求两个数和的相反数是否存在于这个数组中。可以延伸到K sum的问题。
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(num); int start = 0; while (start < num.length-2) { if (start == 0 || num[start] != num[start-1] ) { //留意判断条件,之前写的是start与start+1不等,导致一直不对。。 int instart = start+1; int inlast = num.length-1; while (instart < inlast) { if (num[instart] + num[inlast] == -num[start]) {//这里可以考虑用二分法查找来优化。 List<Integer> temp = new ArrayList<Integer>(); temp.add(num[start]); temp.add(num[instart]); temp.add(num[inlast]); list.add(temp); do { inlast--;//重复的数在这里直接跳过。 } while (num[inlast] == num[inlast+1] && instart < inlast); do{ instart++; } while(num[instart] == num[instart-1] && instart < inlast); }else if (num[instart] + num[inlast] > -num[start]) { inlast--; }else { instart++; } } } start++; } return list; } }
Runtime: 358 ms
更多收获可参考([b]个人觉得很棒):[/b]Summary for LeetCode 2Sum, 3Sum,
4Sum, K Sum
相关文章推荐
- leetcode question 15 : 3Sum
- leetcode-15-3sum
- leetcode15---3Sum
- leetcode-15 3Sum
- leetcode 15 : 3sum
- Leetcode 15 [medium]--3Sum
- [Leetcode] 15 - 3Sum
- LeetCode15 3Sum
- 【一天一道LeetCode】#15 3Sum
- LeetCode:3Sum_15
- leetcode-15 3Sum
- [LeetCode] 15. 3Sum
- leetcode 15 3Sum
- [LeetCode]--15. 3Sum
- [leetcode 15] 3Sum
- 【leetcode】【15】3Sum
- [leetcode] 15. 3Sum 解题报告
- leetcode 15 3Sum
- leetcode(15)3sum
- leetcode-15-3sum