zoukankan      html  css  js  c++  java
  • 15. 三数之和

    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

    注意:答案中不可以包含重复的三元组。

    示例:

    给定数组 nums = [-1, 0, 1, 2, -1, -4],

    满足要求的三元组集合为:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/3sum

    分治+双指针

    /**
     * @param {number[]} nums
     * @return {number[][]}
     */
    var threeSum = function(nums) {
        if(nums.length<3)return [];
        const list=[];
        nums.sort((a,b)=>a-b);
        for(let i=0;i<nums.length;i++){
            if(nums[i]>0)break;
            if(i>0&&nums[i]===nums[i-1])continue;
            let left=i+1;
            let right=nums.length-1;
            while(left<right){
                if(nums[i]+nums[left]+nums[right]===0){
                    list.push([nums[left],nums[right],nums[i]]);
                    while(nums[left]===nums[left+1]){
                        left++;
                    }
                    left++;
                    while(nums[right]===nums[right-1]){
                        right--;
                    }
                    right--;
                    continue;
                }
                else if(nums[i]+nums[left]+nums[right]>0){
                        right--; 
                }
                else{
                    left++;
                }
            }
        }
        return list;
    };
  • 相关阅读:
    CSS3--box-shadow
    C#快捷键
    c#基础3
    C#基础2
    C#基础
    javascript 字符串总结
    javasrcipt中的for in 循环
    javascript复习总结
    结构体数组排序
    ArrayList集合排序
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13769828.html
Copyright © 2011-2022 走看看