leetcode 169. Majority Element
Boyer-Moore majority vote algorithm
By definition, the majority element has to appear more than half of times, so there can only be one majority element. Using the Boyer-Moore majority vote algorithm, we keep count of the times our tmp candidate weighs: if it appears once, we add one to the count; if another candidate appears, we decrement the count by one. When the count is 0, we will set the current candidate to be the new candidate. After we loop through the entire array, the last one candidate left is the majority element we are looking for, because it has not been balanced out by other numbers and therefore it appears the most of times.
class Solution {
public int majorityElement(int[] nums) {
int counter = 1;
int candidate = nums[0];
for (int i=1; i < nums.length; i++){
if (counter == 0) {
candidate = nums[i];
}
if (nums[i] == candidate){
counter++;
} else {
counter--;
}
}
return candidate;
}
}