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.code
Example:排序
Given array nums = [-1, 0, 1, 2, -1, -4],three
A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]ip
和TwoSum整體思想差很少,可是要多一層外循環,枚舉每個target的值,target的值爲0-nums[i], 咱們能夠作一些優化在減小遍歷次數:
1.正數直接跳出,由於排序後後面的確定都是正數
2.和前一個數相同的值能夠直接continueelement
注意幾種特殊狀況[-1,0,1,2,-1,-4],排序後爲[-4,-1,-1,0,1,2],[-2,0,0,2,2],push的時候判斷下左指針和右指針與上個位置的是否相等,注意這裏的條件是或,若是有一個不相等,且值和爲target便可pushget
/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { let ans = []; nums.sort((a,b) => a-b || -1); let len = nums.length; for(let i = 0; i < len; i++) { if(nums[i] > 0) break; if(i>0 && nums[i]===nums[i-1]) continue; let target = 0 - nums[i]; let l = i+1,r=len-1; while(l<r) { if(nums[l]+nums[r]===target && (((l-1>=0)&&nums[l]!==nums[l-1])||(nums[r]!==nums[r+1]&&(r+1<=len))) ) { let t = []; t.push(nums[i],nums[l],nums[r]); ans.push(t); l++; r--; }else if(nums[l]+nums[r]<target) { l++; }else if(nums[l]+nums[r]>target) { r--; }else { l++; r--; } } } return ans; }; console.log(threeSum([-1,0,1,2,-1,-4]));