js三数之和

<!--   [-1,0,1,2,-1,-4]  找出三个数的和为零  [-1,0,1] [-1,-1,2] -->
/* 
    遍历数组
    if当前数字等于前一个数字则跳过
    if数字不同,则设置start=i+1,end=length-1 
    start ,i ,end和比零大end--,比零小start++
    等于0就返回三个数
  */
 var threeSum=function(nums){
  const result=[]
  nums.sort((a,b)=>{
    return a-b
  })
  for(let i=0;i<nums.length-2;i++){
    if(i===0 || nums[i] !== nums[i-1]){
      let start=i+1;
      let end=nums.length-1;
      while(start <end){
        if(nums[i]+nums[start] +nums[end]===0){
          result.push(nums[i],nums[start],nums[end]);
          start++;
          end--;
          while(start<end && nums[start] === nums[start-1]){
            start++;
          }
          while(start<end && nums[end] === nums[end+1]){
            end--;
          }
        }else if(nums[i]+nums[start]+nums[end]<0){
          start++;
        }else{
          end--;
        }
    }
  }
  }
 }
posted @ 2022-06-20 23:20  残星落影  阅读(163)  评论(0)    收藏  举报