虽然是个简单题,还挺有东西的。
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
func majorityElement(nums []int) int {
res := -1 //define a candidate
count := 0 // we need a counter
for i := 0; i < len(nums); i++ {
if count == 0 {
//current count is 0
//which means candidate need to be changed
res = nums[i]
}
if nums[i] == res {
count++
}else{
count--
}
}
return res
}
这种方法好像叫做投票算法。
只能是应用在目标出现次数大于一半,如果题目只是限定了寻找众数,而没有限定一半以上就只能,用map映射了。