Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
思路是先排序,然后for循环确定第一个数字,然后剩下的两个数字按照two sum的方法来做(low+high指针夹逼)。
值得注意的是判断是否存在重复的方式。一开始我想的是用list.contains,但是这样做太费时了,还是应该先利用好已经排序这一点,用基本的“==”来判断。
class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if(nums.length < 3) return res; Arrays.sort(nums); //给数组排序 int low; int high; for(int i=0; i<= nums.length-3; i++){ if (i == 0 || (i > 0 && nums[i] != nums[i-1])) { int sum = 0 - nums[i]; low = i + 1; high = nums.length-1; while(low < high) { if(nums[low] + nums[high] < sum) low++; else if(nums[low] + nums[high] > sum) high--; else { // if(!res.contains(Arrays.asList(nums[i], nums[low], nums[high]))){用这个判断是否重复的话时间太久了 //又是没见过的用法 res.add(Arrays.asList(nums[i], nums[low], nums[high])); // } while(low<high && nums[low] == nums[low+1]) low++; while(low<high && nums[high] == nums[high-1]) high--; low++; high--; } } } } return res; } }