The algorithm relies on a cancellation idea:
[0,1,**2,2**,3] or [0,1,**2,2**] doesn’t have the majority element, the most common element 2 will be cancel out by the end of the Boyer-Moore Voting process.[0,1,**2,2,2**] has the majority element and it is the majority element.https://leetcode.com/problems/majority-element/description/
Last review: Sep 14, 2025 Next review: I couldn’t recall the essential concept.
O(n)O(n)func majorityElement(nums []int) int {
n := len(nums)
count := make(map[int]int)
for _, num := range nums {
count[num]++
if count[num] > n/2 {
return num
}
}
return -1
}
O(n log n)O(log n)func majorityElement(nums []int) int {
n := len(nums)
sort.Ints(nums)
L := 0
for R := 0; R < n; R++ {
if nums[R] != nums[L] {
L = R
}
if R-L+1 > n/2 {
return nums[R]
}
}
return -1
}
O(n)