美文网首页LeetCode By Go
[LeetCode By Go 42]169. Majority

[LeetCode By Go 42]169. Majority

作者: miltonsun | 来源:发表于2017-08-22 09:59 被阅读3次

    题目

    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
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 42]169. Majority

        本文链接:https://www.haomeiwen.com/subject/hevkdxtx.html