leetcode 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] ]
和TwoSum总体思想差不多,但是要多一层外循环,枚举每一个target的值,target的值为0-nums[i], 我们可以做一些优化在减少遍历次数:
1.正数直接跳出,因为排序后后面的肯定都是正数
2.和前一个数相同的值可以直接continue
注意几种特殊情况[-1,0,1,2,-1,-4],排序后为[-4,-1,-1,0,1,2],[-2,0,0,2,2],push的时候判断下左指针和右指针与上个位置的是否相等,注意这里的条件是或,如果有一个不相等,且值和为target即可push
/**
* @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]));