+ 1

How to find the most common number in array? (JAVA)

Input: The first line is the number of elements in the array N (N<=10^6). The second line contains N integers a[i] are the elements in the array (0 <= a[i] < 10^6 ) Output: Output the value and the number of times occur in the array. If there are many number have the same frequency, output minimum number. Problem: I try input 100000 elements and the program takes so much time to display output. Is there any way to improve the speed. Here is my code: https://code.sololearn.com/cO9xU2e0G0dL/?ref=app

26th Nov 2022, 12:13 PM
KatThy
3 Answers
+ 1
For example: length is 4. The elements of this array are 4 3 4 3. Ouput: 3 2 (3 and 4 appears twice, but the program output only smaller number which is 3). Another example: length 6. elements 6 8 8 8 6 1. output 8 3 (8 occurs three times > 6 which appears twice)
26th Nov 2022, 1:50 PM
KatThy
0
You can omit repeated numbers checking again. For example: if array has 4,4,4,4 then you can check count only for one time. You code checks 4 times. Find a way it.( You can use a Set of the array elements to check. Or sort array before then skip count times for next time.. ) Start loop from i=1 in findCommonNumber(). Try to use less variables... for example in input() method, no need of enterNumber variable. you can directly store array[i] = in.nextInt();
26th Nov 2022, 1:53 PM
Jayakrishna 🇮🇳
Jayakrishna 🇮🇳 - avatar
0
Thank you everyone
27th Nov 2022, 7:25 AM
KatThy