力扣——三数之和

题目描述

给你一个包含 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]]

代码

let threeSum = function(nums) {
    let n1 , n2 , n3
    //先从小到大排序
    nums.sort((a , b) => (a - b))
    // 存值数组
    let arr = []
    for(let i = 0 ; i < nums.length - 1 ; i ++) {
        n1 = nums[i] // 令n1为最小的数字
        if(n1 > 0 ) break // 最小的数都是0 了,肯定不用继续了
        if(n1 === nums[i - 1]) continue // 遍历到相同的数字,就跳过

        // 设置左右两个指针
        let left = i + 1
        let right = nums.length - 1

        while(left < right) {
            n2 = nums[left]
            n3 = nums[right]
            if(n1 + n2 + n3 === 0)  {
                arr.push([n1 , n2 , n3])
                // 如果后面遍历到重复的数,指针向前走
                while(n2 === nums[left]) left ++
                while(n3 === nums[right]) right --
            }
            // 三个数之和大于0 ,说明最大的数大了,右指针往左走
            else if(n1 + n2 + n3 > 0) right -- 
            // 反之
            else left ++
        }
        
    }
    return arr
}

posted @ 2022-04-12 15:13  Tricia11  阅读(20)  评论(0)    收藏  举报  来源