【leetcode】169.majority element

此题有多种解法,具体可以查看coder_orz的博客,
链接: https://blog.csdn.net/coder_orz/article/details/51407713

题目描述
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
给定一个长度为n的字符串,找到其中的多数元素。多数元素是出现次数超过n/2的元素。
You may assume that the array is non-empty and the majority element always exist in the array.
假定序列非空,并且主要元素总是存在的。

思路一
(HashTable)遍历数组,用一个字典记录所有出现过的元素及其个数。由于题目说明多数元素一定存在,故当找到某个元素出现次数大于 ⌊ n/2 ⌋ 时即可停止。
代码

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        digits = {}
        for i in nums:
            digits[i] = digits.get(i,0) + 1 #字典的get函数:返回key->键值i对应的数;如果key不存在,返回0
            if digits[i] > len(nums)/2:
                return i

与这个思路类似,也可以考虑用集合这一数据结构。先找出数组中的所有不同的数,相当于“取原数组的集合”的操作,然后判断该集合中的每个数在数组中出现次数是否过半。
代码(56ms)

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums_set = set(nums)
        for i in nums_set:
            if nums.count(i) > len(nums)/2:
                return i

思路二
先对数组进行排序,排序后序列中间位置的数一定是多数元素。

代码(44ms)

        nums.sort()
        return nums[int(len(nums)/2)]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值