Majority Element
Majority element: an element that occurs repeatedly for more than half of the elements of the input.
Boyer-Moore Voting Algorithm
Boyer–Moore majority vote algorithm: finds the majority of a sequence of elements using linear time and constant space.
1
2
3
4
5
6
7
8
9
10
int majorityElement(vector<int>& nums) {
int cnt = 0, candidate = numeric_limits<int>::max();
for (int num : nums) {
if (cnt == 0) {
candidate = num;
}
cnt += (num == candidate) ? 1 : -1;
}
return candidate;
}
This post is licensed under CC BY 4.0 by the author.