Cod sursa(job #2076514)

Utilizator sebi_andrei2008Lazar Eusebiu sebi_andrei2008 Data 26 noiembrie 2017 18:21:38
Problema Elementul majoritar Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.45 kb
package com.company;

import java.io.*;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {

    private static PrintWriter printWriter;
    private static MyScanner scanner;

    public static void main(String[] args) throws IOException {
        scanner = new MyScanner("elmaj.in");
        printWriter = new PrintWriter("elmaj.out");

        HashMap<MyInt, MyInt> hashTable = new HashMap<>();
        int n;
        boolean found = false;
        MyInt foundKey = null;
        MyInt foundValue = null;
        n = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            MyInt x = new MyInt(scanner.nextInt());
            MyInt newValue = new MyInt(1);
            if (hashTable.containsKey(x)) {
                newValue = new MyInt(hashTable.get(x).value + 1 );
            }

            if (newValue.value > n/2) {
                found = true;
                foundKey = x;
                foundValue = newValue;
            }
            hashTable.put(x, newValue);
        }

        if (found) {
            printWriter.printf("%d %d", foundKey.value, foundValue.value);
        } else {
            printWriter.print(-1);
        }

        printWriter.close();
        scanner.close();
    }

    private static class MyScanner
    {
        private BufferedReader bufferedReader;
        private StringTokenizer stringTokenizer;

        MyScanner(String filename) throws FileNotFoundException {
            bufferedReader = new BufferedReader(new FileReader(filename));
        }

        private String next() throws IOException {
            while(stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
                stringTokenizer = new StringTokenizer(bufferedReader.readLine());
            }
            return stringTokenizer.nextToken();
        }

        int nextInt() throws IOException {
            return Integer.parseInt( next() );
        }

        void close() throws IOException {
            bufferedReader.close();
        }
    }

    static class MyInt {
        public int value;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            MyInt myInt = (MyInt) o;

            return value == myInt.value;
        }

        @Override
        public int hashCode() {
            return value;
        }

        public MyInt(int value) {
            this.value = value;
        }
    }
}