Pergunta de entrevista da empresa Apple

find the most frequent element in an integer array

Respostas da entrevista

Sigiloso

21 de out. de 2015

Your code is wrong LK: if (max < mp.getValue()) { max = mp.getKey(); } you are comparing max which stores the KEY, with the VALUE of the other keys in the dictionary. Basically if you have 15 appearing once, and 4 appearing 10 times, you are gonna return 15 as value most appeared. Of course you need another variable to keep trace at the same time of the key, and the current max value (number of appearing). Finally, you could do this during the first cycle. The second is not needed.

1

Sigiloso

31 de out. de 2015

We can use a map to store the value of the number and its corresponding counter. Time complexity would be O(n) and Space would be O(n) as we are using a map data structure. Map map = new HashMap(); for(int i=0; i entry : map.entrySet()){ if(entry.getValue() > counter){ counter = entry.getValue(); number = entry.getKey(); } } System.out.println(number + " === "+counter);

1

Sigiloso

5 de out. de 2015

public static int max(int[] array) { if (array.length == 1) { return array[0]; } Map map = new TreeMap(); for (int i = 0; i mp : map.entrySet()) { if (max < mp.getValue()) { max = mp.getKey(); } } return max; }

1