E
E
Elnur Tazhimbetov2017-09-17 14:23:46
Java
Elnur Tazhimbetov, 2017-09-17 14:23:46

Maximum number of duplicate elements in an array?

There is an array with numbers, you need to find the maximum number of identical elements. For example array a = {1,1,1,3,4,5,6,4,3,2,1,3,4,1,2,3,1,2} and the answer should be 1-6 (six units)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2017-09-17
@tazhimbetov

If the numbers are integer, non-negative and small, then just create a second array to count how many times each number has occurred in it. When increasing the counter, immediately check the value for the maximum.
Something like this:

maxval = -1;
maxcount=0;
for (i = 0; i < n; ++i) {
  ++counts[a[i]];
  if (counts[a[i]] > maxcount) {
    maxcount = counts[a[i]];
    maxval = a[i];
  }    
}

If the numbers are large, then you can replace the counts[] array with a hash map.
If the memory restrictions are severe, then you will have to sort the array and you can already easily calculate how many times each number occurs in it.

E
Eugene Khrustalev, 2017-09-18
@eugenehr

It is possible through Stream, but you can’t do without an intermediate collect

Stream.of(1, 1, 1, 3, 4, 5, 6, 4, 3, 2, 1, 3, 4, 1, 2, 3, 1, 2)
    // Собрать в Map, где ключ - число из массива, значение - кол-во этих чисел в массиве
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
    // Отсортировать EntrySet по убыванию значений
    .entrySet()
    .stream()
    .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue()))
    // Взять первую (если есть) и вывести в консоль 
    .findFirst().ifPresent(e -> System.out.println(e.getKey() + " - " + e.getValue()));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question