zoukankan      html  css  js  c++  java
  • 15. 3Sum(js)

    15. 3Sum

    Given an array nums of n integers, are there elements abc in nums such that a + bc = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    The solution set must not contain duplicate triplets.

    Example:

    Given array nums = [-1, 0, 1, 2, -1, -4],
    
    A solution set is:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]
    题意:给定一个数字数组,抽取三项值相加等于0,找出所有符合要求的情况
    代码如下(js):
    var threeSum = function(nums) {
         var res=[];
    // 1.对数组从小到大排序
         nums=nums.sort((a,b)=>a-b);
         for(var i=0;i<nums.length;i++){
    // 2. 三数相加等于0,说明最小的那个数字一定为负数
             if(nums[i]>0) break;
             if(i>0 && nums[i]===nums[i-1]) continue;
             var target=0-nums[i];
             var j=i+1,k=nums.length-1;
    // 3. 确定好最小数nums[i],然后再找到较大的两数相加等于-nums[i](target)的项
             while(j<k){
                 if(nums[j]+nums[k]==target) {
    // 4.找到符合要求的值存入res,重复的项跳过
                     res.push([nums[i],nums[j],nums[k]]);
                     while(j<k && nums[j] ===nums[j+1]) ++j;
                     while(j<k && nums[k] === nums[k-1]) --k;
                     ++j;--k;
                 }else if(nums[j]+nums[k]<target) ++j;
                 else --k;
             }
         }
         return res;
    };
  • 相关阅读:
    java中判断文件存在与否
    crontab安装以及定时任务的执行
    su命令学习
    linux中如何查看哪些用户允许登录
    linux中的压缩文件的格式
    R语言学习(瑞士军刀)
    linux下mysql导入导出sql文件
    创建线程池的7种方法
    docker运行tomcat
    Docker之镜像
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10381027.html
Copyright © 2011-2022 走看看