algorighm/leetcode/中等/三数之和.js
2024-05-19 03:37:13 +08:00

60 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
给定一个包含 n 个整数的数组 nums判断 nums 中是否存在三个元素 a b c ,使得 a + b + c = 0 ?请找出所有和为 0 且 不重复 的三元组。
示例 1
输入nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2
输入nums = []
输出:[]
示例 3
输入nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
*/
/**
* @param {number[]} nums
* @return {number[][]}
*/
const threeSum = (nums) => {
const result = [];
nums.sort((a, b) => a - b); // 对数组进行排序方便找取target
const len = nums.length;
for (let i = 0; i < len; i++) {
if (nums[i] > 0) break; // 由于数组是有序的如果第一个数大于0后面的无论怎么相加都会大于零
if (i > 0 && nums[i] === nums[i - 1]) continue; // 出现重复直接跳过本次循环
let left = i + 1;
let right = len - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
// nums[left] + nums[right] === target, 这就是我们要找的结果集,
result.push([nums[i], nums[left], nums[right]]);
// 如果left后面的数与left相等就跳过
while (left < right && nums[left] === nums[left + 1]) left++;
// 如果right前面的数与right相等就跳过
while (left < right && nums[right] === nums[right - 1]) right--;
left++;
right--;
}
}
}
return result;
};
console.log(threeSum([-2, 0, 3, -1, 4, 0, 3, 4, 1, 1, 1, -3, -5, 4, 0]));