题目
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
解题思路
遍历数组nums,将元素放入map中,值为元素的数量,如果某元素数量已经大于 ⌊ n/2 ⌋ ,则该元素就是要找的主要元素
代码
func majorityElement(nums []int) int {
var ret int
var majorityMap map[int]int
majorityMap = make(map[int]int)
len1 := len(nums)
for i := 0; i < len1; i++{
num := nums[i]
majorityMap[num]++
if majorityMap[num] > len1/2 {
ret = num
break
}
}
return ret
}