[LeetCode By Go 42]169. Majority Element

题目

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
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/d81cca3e1c8b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞