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] ]
三数之和。题意是给一个input数组,请问是否能找到这样的组合使得a + b + c = 0?输出所有这样的[a, b, c]组合。
还是two sum的思路,双指针从两边往中间逼近。因为和是0,所以可以先固定a的位置,然后找是否有b + c = 0 - a的组合。首先需要对数组排序,然后在执行过程中需要排除一些重复数字,避免最后的output有重复。同时,在遍历a的范围的时候,如果a > 0就可以直接跳过了,因为数组是排序过的,如果a大于0,b,c也必定大于0。
时间O(n^2)
空间O(n^2) - list of list
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number[][]} 4 */ 5 var threeSum = function(nums) { 6 const res = []; 7 let left, right, sum; 8 nums.sort((a, b) => a - b); 9 for (let i = 0; i < nums.length - 2; i++) { 10 if (nums[i] > 0) break; 11 if (nums[i] === nums[i - 1]) continue; 12 left = i + 1; 13 right = nums.length - 1; 14 sum = 0 - nums[i]; 15 while (left < right) { 16 if (nums[left] + nums[right] === sum) { 17 res.push([nums[i], nums[left], nums[right]]); 18 while (left < right && nums[left] === nums[left + 1]) { 19 left++; 20 } 21 while (left < right && nums[right] === nums[right - 1]) { 22 right--; 23 } 24 left++; 25 right--; 26 } else if (nums[left] + nums[right] < sum) { 27 left++; 28 } else { 29 right--; 30 } 31 } 32 } 33 return res; 34 };
Java实现
1 class Solution { 2 public List<List<Integer>> threeSum(int[] nums) { 3 Arrays.sort(nums); 4 List<List<Integer>> res = new ArrayList<>(); 5 for (int i = 0; i < nums.length - 2; i++) { 6 if (i > 0 && nums[i] == nums[i - 1]) { 7 continue; 8 } 9 int sum = 0 - nums[i]; 10 int low = i + 1; 11 int high = nums.length - 1; 12 while (low < high) { 13 if (nums[low] + nums[high] == sum) { 14 res.add(Arrays.asList(nums[i], nums[low], nums[high])); 15 while (low < high && nums[low] == nums[low + 1]) { 16 low++; 17 } 18 while (low < high && nums[high] == nums[high - 1]) { 19 high--; 20 } 21 low++; 22 high--; 23 } else if (nums[low] + nums[high] < sum) { 24 low++; 25 } else { 26 high--; 27 } 28 } 29 } 30 return res; 31 } 32 }