zoukankan      html  css  js  c++  java
  • 在一个无序整数数组中,找出连续增长片段最长的一段, 增长步长是1。Example: [3,2,4,5,6,1,9], 最长的是[4,5,6]

    在一个无序整数数组中,找出连续增长片段最长的一段, 增长步长是1。Example: [3,2,4,5,6,1,9], 最长的是[4,5,6]

    下面是我自己的编写的代码,感觉还能再优化。

    希望有大神可以分享一下自己的解决方案

     1 let arr = [3,2,1,14,5,5,8,1,2,3,4,5,6,76,7,1,2,9];
     2 
     3 function fn(arr){
     4     let temp = [];
     5     let sub = [];
     6     for ( let i = 0; i < arr.length; i++ ){
     7         if(arr[i]+1 === arr[i+1]){
     8             temp.push(arr[i]);
     9         }else{
    10             if(temp.length!=0){
    11                 let temp1 = [];
    12                 temp.push(arr[i]);
    13                 
    14                 for( let i = 0 ; i < temp.length; i++){
    15                     temp1.push(temp[i])
    16                 }
    17                 
    18                 if(sub.length===0||sub.length<temp1.length){
    19                     sub = temp1
    20                 }
    21                 temp = [];
    22             }
    23         }
    24     }
    25     return sub;
    26 }
    27 let arr1 = fn(arr);
    28 console.log(arr1);
  • 相关阅读:
    2017.4.6下午
    2017.4.6上午
    2017.3.31下午
    2017.4.5下午
    2017.4.5上午
    2017.4.1上午
    2017.3.31上午
    2017.3.28下午
    2017.3.28上午
    3.28上午
  • 原文地址:https://www.cnblogs.com/ligusuni/p/9571023.html
Copyright © 2011-2022 走看看