Answer the question
In order to leave comments, you need to log in
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
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];
}
}
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 questionAsk a Question
731 491 924 answers to any question