Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class MostFrequent {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int n = Integer.parseInt(scanner.nextLine());
- int[] elements = new int[n];
- for (int i = 0; i < elements.length; i++) {
- elements[i] = Integer.parseInt(scanner.nextLine());
- }
- //SORTING the integers
- for (int i = 0; i < elements.length; i++) {
- for (int j = i+1; j < elements.length; j++) {
- int temporary = 0;
- if (elements[i] > elements[j]) {
- temporary = elements[i];
- elements[i] = elements[j];
- elements[j] = temporary;
- }
- }
- }
- int count = 1;
- int maxCount = 0;
- int mostCommonNumber = 0;
- for (int i = 0; i < elements.length + 1; i++) {
- if (i == elements.length - 1) {
- break;
- }
- if (elements[i] == elements[i+1]) {
- count++;
- if (i == elements.length - 2 && maxCount < count) {
- maxCount = count;
- mostCommonNumber = elements[i];
- }
- } else {
- if (maxCount < count) {
- maxCount = count;
- mostCommonNumber = elements[i];
- }
- count = 1;
- }
- }
- System.out.printf("%d (%d times)", mostCommonNumber, maxCount);
- }
- }
Add Comment
Please, Sign In to add comment