目录
169-求众数
访问量:1970

一、题目

题目地址:https://leetcode-cn.com/problems/majority-element

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

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


示例 1:

输入: [3,2,3]

输出: 3


示例 2:

输入: [2,2,1,1,1,2,2]

输出: 2

二、解法

1、穷举法

思路:遍历数组的同时,计算出每个数字出现的次数,若出现的次数大于n/2,则停止遍历并返回

func MajorityElement(nums []int) int {
   arrLen := len(nums)
   compVal := arrLen / 2

   sumTimes := make(map[int]int)
   for _, val := range nums {
      sumTimes[val] += 1
      if sumTimes[val] > compVal {
         return val
      }
   }

   return 0
}