Featured image of post 剑指 Offer 39. 数组中出现次数超过一半的数字

剑指 Offer 39. 数组中出现次数超过一半的数字

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

  • 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
  • 输出: 2

限制:

1 <= 数组长度 <= 50000

注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/

解法一:排序

1
2
3
4
func majorityElement(nums []int) int {
    sort.Ints(nums)
    return nums[len(nums)/2]
}

解法二:随机化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func majorityElement(nums []int) int {
    n := len(nums)
    rand.New(rand.NewSource(time.Now().UnixNano()))
    for {
        candidate, cnt := nums[rand.Intn(n)], 0
        for i := 0; i < n; i++ {
            if nums[i] == candidate {
                cnt++
            }
        }
        if cnt > n/2 {
            return candidate
        }
    }
    return -1
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/07/02 09:59:35
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计