15. 3Sum(js)
15. 3Sum
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] ]
题意:给定一个数字数组,抽取三项值相加等于0,找出所有符合要求的情况
代码如下(js):
var threeSum = function(nums) { var res=[]; // 1.对数组从小到大排序 nums=nums.sort((a,b)=>a-b); for(var i=0;i<nums.length;i++){ // 2. 三数相加等于0,说明最小的那个数字一定为负数 if(nums[i]>0) break; if(i>0 && nums[i]===nums[i-1]) continue; var target=0-nums[i]; var j=i+1,k=nums.length-1; // 3. 确定好最小数nums[i],然后再找到较大的两数相加等于-nums[i](target)的项 while(j<k){ if(nums[j]+nums[k]==target) { // 4.找到符合要求的值存入res,重复的项跳过 res.push([nums[i],nums[j],nums[k]]); while(j<k && nums[j] ===nums[j+1]) ++j; while(j<k && nums[k] === nums[k-1]) --k; ++j;--k; }else if(nums[j]+nums[k]<target) ++j; else --k; } } return res; };