Problem 310
Majority Element II
Medium · 20 pts · Array, Hash Table, Counting
Problem
Find every value that appears more than N / 3 times in the array (strictly more than floor(N / 3) times). There can be at most two such values. Print them in increasing order, or -1 if no value appears that often. The Boyer-Moore voting idea extends to this problem with two candidates, but any correct method is accepted.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print the qualifying values in increasing order, separated by spaces, or -1.
Constraints
1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000
Example input
3 3 2 3
Example output
3
Explanation
In 3 2 3 the threshold is floor(3 / 3) = 1, so a value needs at least 2 occurrences. Only 3 appears twice, so the answer is 3.