找出数组中最长的连续数字序列(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]

原文地址:https://www.cnblogs.com/iyangyuan/p/3929914.html