【数组】3Sum
题目:
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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- 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)
思路:
设置两个指针,一个指头,一个指尾,用binary search找需要的元素。找到就加上,没有就去下一步。
/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { var n=nums.length,temp=0,res=[]; if(nums.length<3){ return []; } nums.sort(function(a,b){return a-b;}); for(var i=0;i<n-2;i++){ if(nums[i]>0){ break; } for(var j=n-1;j>i+1;j--){ temp=-(nums[i]+nums[j]); var l=i+1,r=j-1; if(nums[l]>temp||nums[r]<temp){ break; } while(l<=r){ var mid=l+Math.floor((r-l)/2); if(nums[mid]==temp){ var arr=[nums[i],nums[mid],nums[j]]; res[res.length]=arr; break; }else if(nums[mid]<temp){ l=mid+1; }else{ r=mid-1; } } } } return res; };