牛客-剑指offer系列题解:数组中出现次数超过一半的数字(三种方法,推荐摩尔投票法)

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

2、数据结构:
数组

3、题解:

方法1:哈希表统计法
设置一个字典,将numbers中的数字和出现的次数对应起来,判断出现大于一半的长度即可。

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        count = {}
        lens = len(numbers)
        for num in numbers:
            if num in count:
                count[num] += 1
            else:
                count[num] = 1
            if count[num] > (lens >> 1):#相当于count[num] > lens /2
                return num
        return 0

方法2:数组排序法
排序,众数超过一半,中点的数一定是所求的值。

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        #排序法
        if not numbers:
            return None
        numbers.sort()
        #判断是否超过1/2
        mid = len(numbers) // 2
        x = numbers[mid]
        count = 0
        for num in numbers:
            if num == x:
                count += 1
            if count > mid :
            	return x
        return  0

方法3:摩尔投票法
正负抵消
伪代码:
在这里插入图片描述

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        #摩尔投票法
        #找到可能的数
        votes = 0
        for num in numbers:
            if votes == 0:
                x = num
            votes += 1 if num == x else -1
        #统计出现的次数
        count = 0
        for num in numbers:
            if num == x:
                count += 1
        return x if count > (len(numbers) >> 1) else 0

4、复杂度分析:
方法1:
时间复杂度:O(N)
空间复杂度:O(N)
方法2:
时间复杂度:O(NlogN)
空间复杂度:O(1)
方法3:
时间复杂度:O(N)
空间复杂度:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值