Removes repeated numbers from the array. There are many answers to such questions on the Internet, but I feel that the best and most correct answer the interviewer asks is not to open up new memory and optimization algorithms.
The idea is as follows:
Point the pointer to the array header and tail respectively. If you want to compare the data between j --, I and {I + 1, j, if you want to wait for data exchange with the j location, if you want to wait for the j -- On the j location, and do not want to wait for the data exchange on the j location, I ++ continues the loop and ends when I = j. For details, see:
First time: [, 1]
I j
Second time: [, 1]
I j
Third time: [, 1]
I j
Fourth: [, 1]
I j
Completed: [, 1]
Ij
The Code is as follows:
Function f (arr ){
Var I = 0, j = arr. length-1;
While (I! = J ){
For (; I <j; I ++ ){
For (var z = I + 1; z <= j; z ++ ){
If (arr [I] = arr [z]) {
While (arr [z] = arr [j]) {// remove numbers such as the j position and the current number of comparisons.
J --;
Arr. pop ();
}
Arr [z] = arr [j] ^ arr [z];
Arr [j] = arr [j] ^ arr [z];
Arr [z] = arr [j] ^ arr [z];
J --;
Arr. pop ();
}
}
}
}
Return arr; // arr. slice (0, I) can be used here without pop );
}
Alert (f ([,]);
However, the number of times compared with the above method is n2-1, obviously the algorithm is not very optimized.
Algorithm Optimization
Function f (arr ){
Var nArr = new Array ();
NArr. push (arr. pop ());
While (arr. length)
NArr = t (nArr, arr. pop ());
Return nArr;
}
Function t (arr, v ){
Var len = arr. length;
If (len = 1 & arr [0] = v)
Return arr;
Else if (len = 1 & arr [0] <v ){
Arr. push (v );
Return arr;
}
Else if (len = 1 & arr [0]> v)
Return [v]. concat (arr );
Var I = Math. ceil (len/2 );
If (arr [I]> v) // compare the values greater
Return t (arr. slice (0, I), v). concat (arr. slice (I, arr. length ));
If (arr [I] <v) // if it is less than the value of the right leaf
Return arr. slice (0, I). concat (t (arr. slice (I, arr. length), v ));
Return arr;
}
Alert (f ([99,100,]);