Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

169. 多数元素 #19

Open
yankewei opened this issue Mar 13, 2020 · 0 comments
Open

169. 多数元素 #19

yankewei opened this issue Mar 13, 2020 · 0 comments
Labels
数组 题目类型为数组 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

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

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

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element

解答

哈希表

如果肯定存在,那么那个元素的数量肯定大于长度的一半

func majorityElement(nums []int) int {
    l := len(nums)
    m := make(map[int]int, l)
    for i := 0; i < l; i++ {
        m[nums[i]]++
        if m[nums[i]] > l/2 {
            return nums[i]
        }
    }
    return 0
}
排序

如果肯定存在,那么排序之后中间的元素肯定是那个值

func majorityElement(nums []int) int {
    sort.Ints(nums)
    return nums[len(nums)/2]
}
投票法

投票法,简单来说就是就是,设置两个变量,一个值value,和这个值出现的次数count。遍历数组,如果和这个值相等就count++,否则count--,当count为零,value也应该变,具体实现

func majorityElement(nums []int) int {
    value, count := nums[0], 0
    for _, v := range nums {
        if count == 0 {
            value = v
        }
        if v == value {
            count++
        } else {
            count--
        }
    }
    return value
}
@yankewei yankewei added 简单 题目难度为简单 数组 题目类型为数组 labels Mar 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数组 题目类型为数组 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant