Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Note: The algorithm should run in linear time and in O(1) space.
Example 1:
Input: [3,2,3]
Output: [3]
Example 2:
Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
func majorityElement(nums []int) []int {
if len(nums) <= 1 {
return nums
}
res := []int{}
n1, cnt1, n2, cnt2 := 0, 0, 0, 0
for _, v := range nums {
if v == n1 {
cnt1++
} else if v == n2 {
cnt2++
} else if cnt1 == 0 {
n1 = v
cnt1++
} else if cnt2 == 0 {
n2 = v
cnt2++
} else {
cnt1--
cnt2--
}
}
cnt1, cnt2 = 0, 0
for _, v := range nums {
if v == n1 {
cnt1++
} else if v == n2 {
cnt2++
}
}
if cnt1 > len(nums)/3 {
res = append(res, n1)
}
if cnt2 > len(nums)/3 {
res = append(res, n2)
}
return res
}