Home  >  Article  >  Web Front-end  >  JavaScript implements listing the longest consecutive number in an array_javascript skills

JavaScript implements listing the longest consecutive number in an array_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:271134browse

Original title:

Given an unordered sequence of integers, find the longest sequence of consecutive numbers.

For example:

Given [100, 4, 200, 1, 3, 2],

The longest continuous sequence of numbers is [1, 2, 3, 4].

The solution given by Xiao Cai:

Copy code The code is as follows:

function maxSequence(array,step){
var _array = array.slice(), //clone array
_step = 1,
​ _arrayTemp = [],
i = 0;
var parseLogic = {
//result container
ParseResults: [],
//set value to array,what's the last array of parseResults
set: function(n){
This.parseResults[this.parseResults.length-1].push(n);
},
//get the last array from parseResults
Get: function(){
Return this.parseResults[this.parseResults.length-1];
},
//put a new array in parseResults
AddItem: function(){
This.parseResults.push([]);
},
//sort parseResults
SortByAsc: function(){
This.parseResults.sort(function(a,b){
           return a.length - b.length;
});
}
};
//check params
_step = step || _step;
//sort array by asc
_array.sort(function(a,b){
Return a - b;
});
//remove repeat of data
for(i = 0;i<_array.length;i ){
If(_array[i] != _array[i 1]){
​ _arrayTemp.push(_array[i]);
}
}
_array = _arrayTemp.slice();
_arrayTemp = [];
//parse array
parseLogic.addItem();
for(i = 0;i<_array.length;i ){
If(_array[i] _step == _array[i 1]){
       parseLogic.set(_array[i]);
Continue;
}
If(_array[i]-_step == _array[i-1]){
       parseLogic.set(_array[i]);
       parseLogic.addItem();
}
}
//sort result
parseLogic.sortByAsc();
//get the max sequence
Return parseLogic.get();
}


Calling instructions:

Method name:

maxSequence(array,step)

Parameter description:

Array: The array to be searched. necessary.

step: sequence step (increment). Optional, default is 1.

Return value:

This method will not change the passed array, but will return a new array containing the largest sequence.

Call example:

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]

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn