JavaScript is used to list the longest consecutive numbers in an array.
Original question:
For an unordered integer sequence, find the longest continuous sequence of numbers.
For example:
Given [100, 4,200, 1, 3, 2],
The longest continuous numerical sequence is [1, 2, 3, 4].
Solution provided by the dish:
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 ();
}
Call description:
Method Name:
MaxSequence (array, step)
Parameter description:
Array: the array to be searched. Required.
Step: sequence step (incremental ). Optional. The default value is 1.
Return Value:
This method does not change the input array and returns a new array containing the maximum sequence.
Call example:
MaxSequence ([,], 1); // return [,]
MaxSequence ([,], 2); // return [, 9]