[LeetCode]3Sum,解题报告
2014-06-13 23:42
369 查看
题目
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.
思路
开始想用深搜解决,后来发现用深搜很难保证结果没有重复的结合,因此采用排序+双指针固定解决思路,同时增加去除重复的判断机制AC代码
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (num.length < 3) { return res; } Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { // avoid duplicate if (i == 0 || num[i] > num[i - 1]) { int start = i + 1; int end = num.length - 1; while (start < end) { int stand = num[i] + num[start] + num[end]; if (stand == 0) { ArrayList<Integer> tmp = new ArrayList<Integer>(); tmp.add(num[i]); tmp.add(num[start]); tmp.add(num[end]); res.add(tmp); start++; end--; //avoid duplicate while (start < end && num[start] == num[start - 1]) { start ++; } while (start < end && num[end] == num[end + 1]) { end --; } } else if (stand > 0) { end--; } else { start++; } } } } return res; } }
后记
在家呆了5天就要回帝都去阿里上班了,不舍得爸妈,努力工作,争取早点财务自由!多花时间陪陪家人。相关文章推荐
- [leetcode] 15. 3Sum 解题报告
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
- LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum
- [LeetCode] 3Sum 解题报告
- [leetcode] 259. 3Sum Smaller 解题报告
- [LeetCode 解题报告]015. 3Sum
- LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
- leetcode解题报告16. 3Sum Closest
- 【LeetCode】3Sum 解题报告
- leetcode解题报告15. 3Sum
- 3Sum LeetCode 解题报告
- [Leetcode] 259. 3Sum Smaller 解题报告
- LeetCode 解题报告 3Sum Closest
- [Leetcode] 15. 3Sum 解题报告
- [LeetCode 解题报告]016. 3Sum Closest
- [LeetCode] Flatten Binary Tree to Linked List 解题报告
- [LeetCode] Permutations 解题报告
- [LeetCode] Substring with Concatenation of All Words 解题报告
- [LeetCode] Roman To Integer 解题报告