Leetcode 169. Majority Element
Given an array nums
of size n
, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
⌊n / 2⌋
times).There are multiple ways to solve this problem, but one of the most efficient methods is the Boyer-Moore Voting Algorithm. This algorithm operates in linear time O(n)
and requires constant space O(1)
.
The Boyer-Moore Voting Algorithm works as follows:
candidate
for the majority element and a count
.candidate
as nums[0]
and count
as 1.count
is 0, set the current element as the candidate
and reset count
to 1.candidate
, increment count
.count
.candidate
at the end of iteration will be the majority element.public class Solution {
public int majorityElement(int[] nums) {
int candidate = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
candidate = nums[i];
count = 1;
} else if (nums[i] == candidate) {
count++;
} else {
count--;
}
}
return candidate;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {2,2,1,1,1,2,2};
System.out.println(sol.majorityElement(nums)); // Output: 2
}
}
O(n)
where n
is the length of the input array nums
. The array is traversed once.O(1)
. Only a few extra variables (candidate
and count
) are used regardless of the input size.This approach ensures that we find the majority element efficiently with minimal use of resources.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?