给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[[-1, 0, 1], [-1, -1, 2]]
const nums = [-1, 0, 1, 2, -1, -4]; const n = nums.length
const ary = {}; let _ary = []
for(let i = 0; i < n; i++){
if(nums[i] === nums[i-1]){// 该处为关键点(去重):判断当前的数是否与前一个相等.
continue;// 若相等则说明从该数开始的所有可能性已经输出,则跳过该数
}else{
for(let j = i + 1; j < n; j++){
for(let k = j + 1; k < n; k++){
if(nums[i] + nums[j] + nums[k] === 0) {
console.log("%d,%d,%d ",nums[i],nums[j],nums[k]);
_ary = [nums[i], nums[j], nums[k]].sort((a,b) => a-b)
ary[_ary.toString()] = _ary
}
}
}
}
}
Object.values(ary)