Open zentan66 opened 3 years ago
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
const res = []
const len = nums.length
nums.sort((a, b) => a - b)
for (let i = 0; i < len; i++) {
if (nums[i] > 0) break
if (i > 0 && nums[i] === nums[i - 1]) continue
let L = i + 1
let R = len - 1
while (L < R) {
const t = nums[i] + nums[L] + nums[R]
if (t === 0) {
res.push([nums[i], nums[L], nums[R]])
while (L < R && nums[L] == nums[L + 1]) L++ // 去重 例如 [-2, 0, 0, 2]
while (L < R && nums[R] == nums[R - 1]) R-- // 去重
L++
R--
} else if (t < 0) {
L++
} else {
R--
}
}
}
return res
}
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。