Use Boyer-Moore Voting Algorithm. Maintain candidate and count; increment count for matching element, decrement for different, updating candidate when count drops to zero.
class Solution:
def majorityElement(self, nums: list[int]) -> int:
res, count = 0, 0
for n in nums:
if count == 0:
res = n
count += (1 if n == res else -1)
return res
class Solution {
public int majorityElement(int[] nums) {
int count = 0, candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}