Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the most popular element in int[] array

Tags:

java

arrays

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7}; 

how can I write a method and return 7?

I want to keep it native without the help of lists, maps or other helpers. Only arrays[].

like image 506
SexyMF Avatar asked Dec 17 '11 15:12

SexyMF


People also ask

What does int [] do in Java?

int[] list; creates a variable named list of type int[]. This variable is capable of referring to an array of ints, but initially its value is null (if it is a member variable in a class) or undefined (if it is a local variable in a method).

What is array [] in Java?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.


1 Answers

Try this answer. First, the data:

int[] a = {1,2,3,4,5,6,7,7,7,7}; 

Here, we build a map counting the number of times each number appears:

Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i : a) {     Integer count = map.get(i);     map.put(i, count != null ? count+1 : 1); } 

Now, we find the number with the maximum frequency and return it:

Integer popular = Collections.max(map.entrySet(),     new Comparator<Map.Entry<Integer, Integer>>() {     @Override     public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {         return o1.getValue().compareTo(o2.getValue());     } }).getKey(); 

As you can see, the most popular number is seven:

System.out.println(popular); > 7 

EDIT

Here's my answer without using maps, lists, etc. and using only arrays; although I'm sorting the array in-place. It's O(n log n) complexity, better than the O(n^2) accepted solution.

public int findPopular(int[] a) {      if (a == null || a.length == 0)         return 0;      Arrays.sort(a);      int previous = a[0];     int popular = a[0];     int count = 1;     int maxCount = 1;      for (int i = 1; i < a.length; i++) {         if (a[i] == previous)             count++;         else {             if (count > maxCount) {                 popular = a[i-1];                 maxCount = count;             }             previous = a[i];             count = 1;         }     }      return count > maxCount ? a[a.length-1] : popular;  } 
like image 151
Óscar López Avatar answered Oct 14 '22 18:10

Óscar López