229. 求众数 II
题目描述:
给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
考察重点:设超过 ⌊ n/3 ⌋ 次的元素有a个,则一定有 ⌊ n/3 ⌋ * a < n。即这种元素至多存在2个。
先用摩尔投票法求出最多的两个元素,再判断二者是否超过 ⌊ n/3 ⌋ 。
func majorityElement(nums []int) []int {
x, y, lx, ly, len := 0, 0, 0, 0, len(nums)/3
for _, num := range nums {
if (x == num || lx == 0) && num != y {
x = num
lx++
} else if y == num || (ly == 0) {
y = num
ly++
} else {
lx--
ly--
}
}
lx, ly = 0, 0
for _, num := range nums {
if num == x {
lx++
}
if num == y {
ly++
}
}
res := []int{}
if lx > len{
res = append(res, x)
}
if ly > len && x != y{
res = append(res, y)
}
return res
}