一、题目地址
https://leetcode-cn.com/problems/3sum/
二、思路链接
https://www.bilibili.com/video/BV1oE411Q7cS?from=search&seid=2369352147865419937&spm_id_from=333.337.0.0
三、具体代码
var threeSum = function(nums) {
const len = nums.length;
if(len < 3) return [];
nums.sort(function(a, b) {
if(a > b) {
return 1;
}else {
return -1;
}
});
let res = [];
for(let i = 0; i < len - 1; i++) {
if(nums[i] > 0) break;
if(i > 0 && nums[i] === nums[i - 1]) continue;
let l = i + 1, r = len - 1;
while(l < r) {
const sum = nums[i] + nums[l] + nums[r];
if(sum < 0) { l++; continue };
if(sum > 0) { r--; continue };
res.push([nums[i], nums[l], nums[r]])
while(l < r && nums[l] === nums[++l]);
while(l < r && nums[r] === nums[--r]);
}
}
return res;
};
|