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:
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:fu Nction (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]