Read numbers in the range 0–100, count how often each appears using an int array, and print every value that appears more than once plus the most frequent value.
Solution
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] count = new int[101];
while (in.hasNextInt()) count[in.nextInt()]++;
int mode = 0;
StringBuilder repeated = new StringBuilder();
for (int v = 0; v <= 100; v++) {
if (count[v] > 1) repeated.append(v).append('x').append(count[v]).append(' ');
if (count[v] > count[mode]) mode = v;
}
System.out.println("repeated: " + repeated.toString().trim());
System.out.println("most frequent: " + mode + " (" + count[mode] + " times)");
}
}
Output Verified by compiling and running
repeated: 64x2 72x4 85x2
most frequent: 72 (4 times)
For a small known range, the value itself is the index into the counting array – O(n) with no sorting or maps.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!