zoukankan      html  css  js  c++  java
  • 找出数组中最长的连续数字序列(JavaScript实现)

    原始题目:

    给定一个无序的整数序列, 找最长的连续数字序列。

    例如:

    给定[100, 4, 200, 1, 3, 2],

    最长的连续数字序列是[1, 2, 3, 4]。

    小菜给出的解法:

     1 function maxSequence(array,step){
     2   var _array = array.slice(),  //clone array
     3       _step = 1,
     4       _arrayTemp = [],
     5       i = 0;
     6   
     7   var parseLogic = {
     8     //result container
     9     parseResults: [],
    10     //set value to array,what's the last array of parseResults
    11     set: function(n){
    12       this.parseResults[this.parseResults.length-1].push(n);
    13     },
    14     //get the last array from parseResults
    15     get: function(){
    16       return this.parseResults[this.parseResults.length-1];
    17     },
    18     //put a new array in parseResults
    19     addItem: function(){
    20       this.parseResults.push([]);
    21     },
    22     //sort parseResults
    23     sortByAsc: function(){
    24       this.parseResults.sort(function(a,b){
    25         return a.length - b.length;
    26       });
    27     }
    28   };
    29   
    30   //check params
    31   _step = step || _step;
    32   
    33   //sort array by asc
    34   _array.sort(function(a,b){
    35     return a - b;
    36   });
    37   
    38   //remove repeat of data
    39   for(i = 0;i<_array.length;i++){
    40     if(_array[i] != _array[i+1]){
    41       _arrayTemp.push(_array[i]);
    42     }
    43   }
    44   _array = _arrayTemp.slice();
    45   _arrayTemp = [];
    46   
    47   //parse array
    48   parseLogic.addItem();
    49   for(i = 0;i<_array.length;i++){
    50     if(_array[i]+_step == _array[i+1]){
    51       parseLogic.set(_array[i]);
    52       continue;
    53     }
    54     if(_array[i]-_step == _array[i-1]){
    55       parseLogic.set(_array[i]);
    56       parseLogic.addItem();
    57     }
    58   }
    59   
    60   //sort result
    61   parseLogic.sortByAsc();
    62   
    63   //get the max sequence
    64   return parseLogic.get();
    65   
    66 }
    View Code

    调用说明:

         方法名称:

             maxSequence(array,step)

         参数说明:

             array:要查找的数组。必要。

             step:序列步长(增量)。可选,默认为1。

         返回值:

             此方法不会改变传入的数组,会返回一个包含最大序列的新数组。

         调用示例:

             maxSequence([5,7,2,4,0,3,9],1);  //return [2,3,4,5]

             maxSequence([5,7,2,4,0,3,9],2);  //return [5,7,9]

  • 相关阅读:
    tp框架 php ajax 登陆
    js代码之编程习惯
    基于bootstrap的后台左侧导航菜单和点击二级菜单刷新二级页面时候菜单展开显示当前菜单
    用WebStorm进行Angularjs 2的开发
    关于datetimepicker只显示年、月、日的设置
    checkbox多选按钮变成单选
    mac navicate破解版汉化
    mac CodeIgniter和EasyWeChat 开发微信公众号
    python settings :RROR 1130: Host 'XXXXXX' is not allowed to connect to this MySQL server
    Eclipse中如何显示代码行
  • 原文地址:https://www.cnblogs.com/iyangyuan/p/3929914.html
Copyright © 2011-2022 走看看