/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function (nums) { let res = []; const len = nums.length; nums = nums.sort((a, b) => (a - b)); for (let i = 0; i < len - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) { continue; }
// 定义双指针 let leftIndex = i + 1; let rightIndex = len - 1;
while (leftIndex < rightIndex) { const sum = nums[i] + nums[leftIndex] + nums[rightIndex]; if (sum === 0) { res.push([ nums[i], nums[leftIndex], nums[rightIndex] ]); while (nums[leftIndex] == nums[leftIndex + 1]) { leftIndex++; } while (nums[rightIndex] == nums[rightIndex - 1]) { rightIndex--; } leftIndex++; rightIndex--; } else if (sum > 0) { rightIndex--; } else if (sum < 0) { leftIndex++; }