JavaScript to find the longest continuous numeric sequence in the array, javascript 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:
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 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([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]
Javascript array determines the number of elements with the same value
How efficient should the landlord be? It's easy. In short, I think it's quite difficult to traverse the two. here is a little bit better. Sort the array first and traverse it. I don't know if it's a little easier. I even don't know... after sorting, traversal may be faster ..
Var strArray = new Array ();
StrArray = {2,100, 2,100, 0}
StrArray. sort (function (a, B) {return a-B ;});
How does javascript remove repeated elements from the array?
Because the length of the array cannot be changed, to "Remove", only one array can be redefined.
// Assume that oldArray is the original array and newArray is the final result. You can create a function.
Function f (Array oldArray ){
Array newArray; // target Array
Var m = oldArray. length;
For (var I = 0; I <m; I ++ ){
Var flag = true;
Var n = newArray. length;
For (var j = 0; j <n; j ++)
If (newArray [j] = oldArray [I])
Flag = false;
If (flag)
NewArray [n] = oldArray [I];
}
Return newArray;
}