给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:nums = [3,2,3]
输出:3
示例 2:
输入:nums = [2,2,1,1,1,2,2]
输出:2
提示:
- n == nums.length
- 1 <= n <= 5 * 10^4
- -10^9 <= nums[i] <= 10^9
进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
解题:
func majorityElement(nums []int) int {
m, n := make(map[int]int), len(nums)
for _, v := range nums {
m[v]++
}
for i, v := range m {
if v > n/2 {
return i
}
}
return 0
}
官方解答:
1.哈希表
func majorityElement(nums []int) int {
counts := make(map[int]int)
majority, cnt := 0, 0
for _, v := range nums {
counts[v]++
if counts[v] > cnt {
majority = v
cnt = counts[v]
}
}
return majority
}
2.排序
func majorityElement(nums []int) int {
sort.Ints(nums)
return nums[len(nums)/2]
}
3.随机化
func majorityElement(nums []int) int {
for {
candidate := nums[rand.Intn(len(nums))]
count := 0
for _, v := range nums {
if v == candidate {
count++
}
}
if count > len(nums)/2 {
return candidate
}
}
}
4.分治
func countInRange(nums []int, target, lo, hi int) int {
count := 0
for i := lo; i <= hi; i++ {
if nums[i] == target {
count++
}
}
return count
}
func majorityElementRec(nums []int, lo, hi int) int {
if lo == hi {
return nums[lo]
}
mid := (lo + hi) / 2
leftMajority := majorityElementRec(nums, lo, mid)
rightMajority := majorityElementRec(nums, mid+1, hi)
if countInRange(nums, leftMajority, lo, hi) > (hi-lo+1)/2 {
return leftMajority
}
if countInRange(nums, rightMajority, lo, hi) > (hi-lo+1)/2 {
return rightMajority
}
return -1
}
func majorityElement(nums []int) int {
return majorityElementRec(nums, 0, len(nums)-1)
}
5.Boyer-Moore投票算法
func majorityElement(nums []int) int {
candidate, count := -1, 0
for _, v := range nums {
if v == candidate {
count++
} else if count--; count < 0 {
candidate = v
count = 1
}
}
return candidate
}