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 sequence of consecutive numbers is [1, 2, 3, 4].
The solution given by Xiaocai:
function maxSequence(array,step){var _array = array.slice(), //clone array_step = 1,_arrayTemp = [],i = 0;var parseLogic = {//result containerparseResults: [],//set value to array,what's the last array of parseResultsset: function(n){this.parseResults[this.parseResults.length-1].push(n);},//get the last array from parseResultsget: function(){return this.parseResults[this.parseResults.length-1];},//put a new array in parseResultsaddItem: function(){this.parseResults.push([]);},//sort parseResultssortByAsc: 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 datafor(i = 0;i<_array.length;i++){if(_array[i] != _array[i+1]){_arrayTemp.push(_array[i]);}}_array = _arrayTemp.slice();_arrayTemp = [];//parse arrayparseLogic.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 resultparseLogic.sortByAsc();//get the max sequencereturn parseLogic.get();}Call instructions:
Method name:
maxSequence(array, step)
Parameter description:
array: The array to be found. necessary.
step: Sequence step (increment). Optional, default is 1.
Return value:
This method does not change the incoming array and returns 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]