Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
- Time: O(n)
- Space: O(1)
Boyer–Moore
public int majorityElement(int[] nums) {
int count = 1, major = nums[0];
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
major = nums[i];
count++;
} else if (major == nums[i]) {
count++;
} else {
count--;
}
}
return major;
}