Telephone Interview algorithm question: Find the elements with the most repeated entries in the array and print
The problem is not difficult. You can give a better solution.
Java code
- Import java. util. hashmap;
- Import java. util. iterator;
- Import java. util. Map. entry;
- Import commons. algorithm. Sort. quicksort;
- /**
- * Find the most repeated elements in the array and print them.
- *
- */
- Public class problem_3 {
- // Search for O (N * log2 (n) + n) cyclically after fast sorting)
- Public static void find1 (INT [] ARR ){
- Quicksort. Sort (ARR );
- Int max = arr [0];
- Int pre = 1;
- Int now = 1;
- For (INT I = 0; I <(ARR. Length-1); I ++ ){
- If (ARR [I] = arr [I + 1])
- Now ++;
- Else {
- If (now> = pre ){
- Pre = now;
- Now = 1;
- Max = arr [I];
- }
- }
- }
- }
- // Nested loop query O (N * n)
- Public static void find2 (INT [] ARR ){
- Int pre = 0;
- Int max = arr [0];
- For (INT I = 0; I <arr. length; I ++ ){
- Int now = 0;
- For (Int J = 0; j <arr. length; j ++ ){
- If (ARR [I] = arr [J]) {
- Now ++;
- }
- }
- If (now> = pre ){
- Max = arr [I];
- Pre = now;
- }
- }
- }
- // Hash
- Public static void find3 (INT [] ARR ){
- Hashmap <integer, integer> Hm = new hashmap <integer, integer> ();
- For (INT I = 0; I <arr. length; I ++ ){
- If (Hm. containskey (ARR [I]) {
- Int COUNT = hm. Get (ARR [I]);
- Hm. Put (ARR [I], ++ count );
- } Else {
- Hm. Put (ARR [I], 1 );
- }
- }
- Iterator <entry <integer, integer> it = hm. entryset (). iterator ();
- Int pre = 0;
- Int max = arr [0];
- While (it. hasnext ()){
- Entry <integer, integer> en = it. Next ();
- Int key = en. getkey ();
- Int val = en. getvalue ();
- If (Val> pre ){
- Pre = val;
- Max = key;
- }
- }
- }
- Public static void main (string ARGs []) {
- // There are more than 800 duplicate elements in the amount of data, which are: 46 3680 195
- Int arr2 [] = {0, 1, 2 ,.....
- , 0, 1, 2, 3, 6, 7, 8, 9 };
- // The amount of data is 800. There are few duplicate elements, and the search time is 82 3727 360.
- Int arr [] = {, 6 ......
- , 730,731, 52, 53, 3,794, 95,796,797,798,799 };
- Long start, end;
- Start = system. currenttimemillis ();
- For (INT I = 0; I <1000; I ++) find1 (ARR );
- End = system. currenttimemillis ();
- System. Out. println (end-Start );
- Start = system. currenttimemillis ();
- For (INT I = 0; I <1000; I ++) find2 (ARR );
- End = system. currenttimemillis ();
- System. Out. println (end-Start );
- Start = system. currenttimemillis ();
- For (INT I = 0; I <1000; I ++) find3 (ARR );
- End = system. currenttimemillis ();
- System. Out. println (end-Start );
- }
- }
Reprinted from: http://leves.javaeye.com/blog/777508