Find longest occurrence of same number in array

前端 未结 12 1509
一生所求
一生所求 2021-01-05 17:49

Using JavaScript, I\'m trying to find a way to find the longest occurrence of the same number (in this case, 1) in an array.

For instance, here\'s a sample array:

12条回答
  •  既然无缘
    2021-01-05 17:59

    Unfortunatly, a question has been marked as duplicate, but it was not the same as this one. So I must put my answer here, sorry…

    let tab = [0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1]
      , arr = []
      , n = 0
      , res = null ;
    
    for(let i of tab)
    {
        if ( i ) { ++ n }
        else if ( n ) { arr.push(n) ; n = 0 }
    }
    arr.push(n) ;
    
    res = Math.max(...arr);
    
    console.log("Streak with 1 is ", Math.max(...arr));

    It's a better solution than with reduce, slower, as you can see:

    let tab = [0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1];
    let arr = [];
    let n = 0;
    let res = null;
    
    let loop = 0;
    let start = new Date().getTime();
    
    while (loop < 1000000){
      ++ loop;
      
      arr = [];
      for(let i of tab)
      {
          if ( i ) { ++ n }
          else if ( n ) { arr.push(n) ; n = 0 }
      }
      arr.push(n);
      res = Math.max(...arr);
    }
    let end = new Date().getTime();
    console.log("laps old fashion = ", end - start);
    
    loop = 0;
    let streaks = null;
    start = new Date().getTime();
    while (loop < 1000000){
      ++ loop;
      streaks = tab.reduce((res, n) => 
        (n ? res[res.length-1]++ : res.push(0), res)
      , [0]);
      res = Math.max(...streaks);
    }
    end = new Date().getTime();
    console.log("laps reduce = ", end - start);
    
    console.log("Streak with 1 is ", Math.max(...arr));

提交回复
热议问题