Majority Element (Boyer-Moore)
Problem
In the array one value appears more than n / 2 times. Print this value. Use O(1) extra memory.
Constraints
- 1 <= n <= 10^5
- A majority element always exists
Examples
Input
7 2 2 1 1 1 2 2
Output
2
Solutions
Boyer-Moore voting: each different pair cancels out. The majority has more than half of all elements, so it can not be fully cancelled.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The majority element.
* Approach: Cancel different pairs.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a) {
// Step 1: candidate is the current guess. votes says how sure we are.
int candidate = 0;
int votes = 0;
for (int value : a) {
// Step 2: When the votes are 0, take the current value as the new guess.
if (votes == 0) {
candidate = value;
}
// Step 3: The same value adds a vote. A different value removes one vote.
votes += (value == candidate) ? 1 : -1;
}
// Step 4: A majority element always survives the cancelling.
return candidate;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- Why can the majority element never be cancelled out?