AlgoMaster Logo

Majority Element

arr=[2, 2, 1, 1, 1, 2, 2]
1public int majorityElement(int[] nums) {
2    // Boyer-Moore Voting Algorithm
3    int candidate = nums[0];
4    int count = 1;
5
6    // Find candidate
7    for (int i = 1; i < nums.length; i++) {
8        if (count == 0) {
9            candidate = nums[i];
10            count = 1;
11        } else if (nums[i] == candidate) {
12            count++;
13        } else {
14            count--;
15        }
16    }
17
18    // The candidate is the majority element
19    return candidate;
20}
0 / 14
20211213142526candidate = 2count = 1