Original topic:
Given a sequence of unordered integers, find the longest sequence of consecutive digits.
For example:
Given [100, 4, 200, 1, 3, 2],
The longest sequential number sequence is [1, 2, 3, 4].
The solution to the side dishes:
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 arrays to find. Necessary.
Step: Sequence Size (increment). Optionally, the default is 1.
return value:
This method does not change the passed-in array, and returns a new array that contains 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]