算法的魅力~
***在给定的长度为n的数组里,找出所有的三个值相加为0的可能性组合。如
nums = [-1, 0, 1, 2, -1, -4]
return
[ [-1, 0, 1], [-1, -1, 2] ];
我的方案:
var threeSum = function (nums) {
let len = nums.length;
let o = {};
let oc = [];//重复的值的集合
let oa = [];//去重
nums = nums.sort((a, b) => a - b);//排序
for (let i = 0; i < len; i++) {
if (o[nums[i]]) {
o[nums[i]]++;
if (o[nums[i]] === 2) oc.push(nums[i]);
}
else {
o[nums[i]] = 1;
oa.push(nums[i]);
}
}
let oal = oa.length;
let rarr = [];
//找出三个值都不同的组合可能性
for (let i = 0; i < oal; i++) {
let s1 = oa[i];
if (s1 >= 0) break;
for (let y = i + 1; y < oal; y++) {
let s2 = oa[y];
let s3 = 0 - s1 - s2;
if (s3 <= 0 || s3 <= s2) break;
if (o[s3]) rarr.push([s1, s2, s3]);
}
}
//找出两个或三个值重复的可能性
for (let i = 0, ocl = oc.length; i < ocl; i++) {
let s1 = s2 = oc[i];
let s3 = 0 - s1 - s2;
if (s3 === 0) {
if (o[s3] > 2) rarr.push([0, 0, 0]);
} else {
if (o[s3]) rarr.push([s1, s2, s3]);
}
}
return rarr;
};
升级版:
var threeSum = function (nums) {
var rtn = [];
if (nums.length < 3) {
return rtn;
}
nums = nums.sort(function (a, b) {
return a - b;
});
for (var i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) {
return rtn;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (var j = i + 1, k = nums.length - 1; j < k;) {
if (nums[i] + nums[j] + nums[k] === 0) {
rtn.push([nums[i], nums[j], nums[k]]);
j++;
k--;
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
} else if (nums[i] + nums[j] + nums[k] > 0) {
k--;
} else {
j++;
}
}
}
return rtn;
};