leetcode(15)3sum
2017-10-05 16:25
344 查看
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]
]
因为本人比较菜,所以一开始想的当然是N3的遍历,但是一个medium的题目肯定不能这么简单,所以这题就理解为成a+b = -c的题目。然后可以用双指针做,遍历num[],0-num[i]作为-c,left指针从i+1开始向右遍历,right从右开始向左遍历。
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]
]
因为本人比较菜,所以一开始想的当然是N3的遍历,但是一个medium的题目肯定不能这么简单,所以这题就理解为成a+b = -c的题目。然后可以用双指针做,遍历num[],0-num[i]作为-c,left指针从i+1开始向右遍历,right从右开始向左遍历。
class Solution { public List<List<Integer>> threeSum(int[] nums) { //先排序 Arrays.sort(nums); //避免重复,将获得的list先放入set中 Set<List> sets = new HashSet<>(); for(int i=0;i<nums.length;i++){ //如果num[i]>0就出现不了=0的情况所以break if (nums[i]>0)break; int target = 0-nums[i]; int j = i+1;int k = nums.length-1;//定义左右指针 while (j<k){ if (nums[j]+nums[k] == target){ List<Integer> set = new ArrayList<>(); set.add(nums[i]);set.add(nums[j]);set.add(nums[k]); sets.add(set); j++;k--; } //如果左右指针的数的sum小于target则从用更大的比较,所以j++,同理,如果小于target,则k--; else if (nums[j]+nums[k]<target){ j++; } else { k--; } } } List<List<Integer>> lists = new ArrayList<>(); for (List list: sets){ lists.add(list); } return lists; } }
相关文章推荐
- leetcode-15 3Sum
- leetcode(15). 3Sum
- LeetCode 15 3Sum
- LeetCode-15-3Sum
- [leetcode] 15. 3Sum
- LeetCode 15 3Sum
- LeetCode - 15. 3Sum
- Leetcode 15 [medium]--3Sum
- leetcode-15 3sum
- LeetCode 15 3Sum
- LeetCode 15 3Sum
- Leetcode 15 3sum
- 3sum leetcode (15)
- LeetCode之15----3Sum
- leetcode15 3Sum(java 实现)
- LeetCode - 15. 3Sum
- leetcode 15 3sum
- [leetcode 15] 3Sum
- leetcode -15 3sum
- Leetcode 15 3Sum + 有趣的小BUG