LeetCode 15. 3Sum
2017-01-07 22:41
148 查看
题目:
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: 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] ]
思路:
简单粗暴,三层循环求结果,失败了。。。因为不好去重。对于输入[-1,0,1,2,-1,-4],我的输出是
[[-1,0,1],[-1,2,-1],[0,1,-1]],期望输出是
[[-1,-1,2],[-1,0,1]]。没有想到太好的改动办法,参考Top Solutions思路,进行了大改。
代码:
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> returnList = new ArrayList<>(); for(int i=0;i<nums.length;i++){ for(int j=i+1;j<nums.length;j++){ for(int k=j+1;k<nums.length;k++){ if(nums[i]+nums[j]+nums[k]==0){ List<Integer> list = new ArrayList<>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[k]); returnList.add(list); } } } } return returnList; }
改进:
先排序,找到可能出现重复的地方直接continue对于输入
[-1,0,1,2,-1,-4],排序后是
[-4,-1,-1,0,1,2],期望输出是
[[-1,-1,2],[-1,0,1]],第二个
-1作为target时就需要跳过,因为第一个
-1为target时已经找出了包含一个
-1和两个
-1的所有情况。
public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> returnList = new ArrayList<>(); for(int i=0;i<nums.length;i++){ if (i > 0 && nums[i] == nums[i - 1]) { //跳过相同结果 continue; } for(int j=i+1;j<nums.length;j++){ if (j>i+1 && nums[j] == nums[j - 1]) { //跳过相同结果 continue; } for(int k=j+1;k<nums.length;k++){ if (k>j+1 && nums[k] == nums[k - 1]) { //跳过相同结果 continue; } if(nums[i]+nums[j]+nums[k]==0){ List<Integer> list = new ArrayList<>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[k]); returnList.add(list); } } } } return returnList; }
再改进:
上面的时间复杂度为n^3,主要因为2Sum的部分,使用两层for循环j,k造成复杂度为n^2。更好的做法是,对于已排序数组的2Sum问题,直接j从小开始,k从大开始,遍历到中间相遇后停下。则只需要n的复杂度。public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> returnList = new ArrayList<>(); for(int i=0;i<nums.length-2;i++){ if (i > 0 && nums[i] == nums[i - 1]) { //跳过相同结果 continue; } int j = i + 1, k = nums.length - 1; while (j < k) { if (nums[i]+nums[j]+nums[k]==0) { returnList.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 (nums[i]+nums[j]+nums[k]>0) { k--; } else { j++; } } } return returnList; }
相关文章推荐
- leetcode题解-15. 3Sum
- 【LeetCode】15. 3Sum
- LeetCode 15. 3Sum
- Leetcode 15. 3Sum
- Leetcode 15. 3Sum
- LeetCode 15. 3Sum
- leetcode 15. 3Sum
- Leetcode15. 3Sum
- Leetcode 1. Two Sum & 15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- LeetCode 15. 3Sum
- leetcode 15. 3Sum
- 【Leetcode】Path Sum from root to leaf in binary tree
- [LeetCode] Binary Tree Maximum Path Sum Solution
- LeetCode Combination Sum II
- leetcode题解-18. 4Sum
- Leetcode_001_Two_Sum
- leetcode 15. 3Sum
- [leetcode] 39& 40 Combination Sum I& II
- leetcode笔记:Combination Sum II
- LeetCode 303. Range Sum Query - Immutable