/**
* @author cookie
* 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
* 注意:答案中不可以包含重复的三元组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
let nums = [1, 0, -1, 11, 89, -98, 10, 34, -56, 56]
/**
* 方法一:
* 三层循环, 问每个数, 适合的拿出来.
* 但是这样的时间复杂度为O(n**3), n的立方.
*
*/
/**
* @param {number[]} nums
* @return {number[][]}
*/
const threeNums = function (nums) {
if (nums.length <= 1) return [];
let res = []
for (let i = 0; i < nums.length - 2; i++) {
for (let j = i + 1; j < nums.length - 1; j++) {
for (let z = j + 1; z < nums.length; z++) {
if (nums[i] + nums[j] + nums[z] === 0) {
res.push([i, j, z])
}
}
}
}
return res;
}
const res = threeNums(nums)
console.log(res);
leetcode 15-三数之和
猜你喜欢
转载自blog.csdn.net/weixin_40944062/article/details/113105137
今日推荐
周排行