Title: Array de-weight, most common types of questions
Five algorithms to achieve this goal:
Array.prototype.unique1 =function(){ varR =NewArray (); Label: for(vari = 0; I < This. length; i++) { for(varj = 0; J < R.length; J + +) { if(R[j] = = This[i]) { Continuelabel; } }; R[r.length]= This[i]; }; returnR;}
Array.prototype.unique2 =function(){ varn = {},r=[];//n is a hash table and r is a temporary array for(vari = 0; I < This. length; i++)//iterate through the current array { if(!n[ This[i]])//If there is no current item in the hash table{n[ This[i]] =true;//Deposit Hash TableR.push ( This[i]);//Push the current item of the current array into the temporary array } } returnR;}
Array.prototype.unique3 =function () { varn = [];//a new temporary array for(vari = 0; I < This. length; i++)//iterate through the current array { //if the current array of I has been saved into a temporary array, then skip, //Otherwise push the current item to the temporary array if(N.indexof ( This[i]) = =-1) n.push ( This[i]); } returnN;}Array.prototype.unique4=function(){ varn = [ This[0]];//result Array for(vari = 1; I < This. length; i++)//start traversing from the second item { //if the item I of the current array first appears in the current array, the position is not I, //then it means that item I is repeated and ignored. Otherwise, the result array is stored if( This. IndexOf ( This[i]) = = i) N.push ( This[i]); } returnN;}
The 4th and 3rd methods all use the IndexOf method of the array. The purpose of this method is to look for the first occurrence of the stored parameter in the array. Obviously, the JS engine will iterate through the array until the target is found by implementing this method. So this function will waste a lot of time. The 2nd method uses a hash table. Deposit an object in the form that has already appeared through the subscript. The reference to the subscript is much faster than searching the array with indexof.
To determine the efficiency of these three methods, I made a test program, generated an array of 10000-length random numbers, and then used several methods to test the execution time. The results show that the second method is much faster than the other two methods. However, the memory footprint should be the second method more, because a hash table. This is the so-called space change time. This is the test page, you can also go to see.
The Fifth method:
Array.prototype.unique4 = function () { this .sort (); var re=[this [0]]; for (var i = 1; i < this . Length; I++ this [i]!== re[re.length-1]) {Re.push ( this [i]); }} return re;}
The idea of this method is to sort the array first and then compare the adjacent two values. When sorting the JS native sort method, the JS engine should be used in a quick sort. The result of the final test is that this method runs for an average of about three times times the second method, but much faster than the first and third methods.
Interview questions: Array de-weight