题解 | #三数之和#
三数之和
http://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
/**
*
* @param num int整型一维数组
* @return int整型二维数组
*/
function threeSum(num) {
// write code here
const res = [];
const size = num.length;
if (size === 0 || size < 3) return res;
num.sort((a, b) => a - b);
for (let i = 0; i < size - 2; i++) {
if (i > 0 && num[i] === num[i - 1]) continue;
let L = i + 1,
R = size - 1;
while (L < R) {
const sum = num[i] + num[L] + num[R];
if (sum === 0) {
res.push([num[i], num[L], num[R]]);
while (L < R && num[L] === num[L + 1]) {
L++;
}
while (L < R && num[R] === num[R - 1]) {
R--;
}
L++;
R--;
} else if (sum < 0) L++;
else if (sum > 0) R--;
}
}
return res;
}
module.exports = {
threeSum: threeSum,
};