summaryrefslogtreecommitdiff
path: root/AlgoDesignAndTechniqueEdxJava/sources/MajorityElement.java
blob: 7ef39774c1268c10ab8f0924f4e60b475370ea7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class MajorityElement {

    public static void main(String[] args) {
        FastScanner scanner = new FastScanner(System.in);
        int n = scanner.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }
        if (getMajorityElement(a, 0, a.length -1) != -1) {
            System.out.println(1);
        } else {
            System.out.println(0);
        }
    }
    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream stream) {
            try {
                br = new BufferedReader(new InputStreamReader(stream));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

	public static int getMajorityElement(int[] a, int left, int right) {
		if (left == right)
			return a[left];
		int middle = (right - left) / 2;
		int b = getMajorityElement(a, left, left + middle);
		int c = getMajorityElement(a, left + middle + 1, right);
		int d = conquer(a, b, c, left, right);
		return d;
	}

	private static int conquer(int[] a, int b, int c, int left, int right) {
		int countB = 0;
		int countC = 0;
		for (int i = left; i < right + 1; i++) {
//		for (int i = 0; i < right + 1; i++) {
			if (a[i] == b)
				countB++;
			if (a[i] == c)
				countC++;
		}
		if (countB > (right - left + 1) / 2)
			return b;
		if (countC > (right - left + 1) / 2)
			return c;
		return -1;
	}

}