版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412904
思路
假设第一个元素是众数,记录它的数量,遍历
如果和众数相等,就递增,否则就递减
如果数量等于0,说明不是众数,重新开始
code
代码语言:javascript复制func majorityElement(nums []int) int {
c := nums[0]
count := 1
for i := 1; i < len(nums); i {
if nums[i] == c {
count
} else {
count--
}
if count < 1 {
count = 1
c = nums[i]
}
}
return c
}