剑指offer_39_数组中出现次数超过一半的数字

时间:2020-07-21 22:51:19   收藏:0   阅读:94

数组中出现次数超过一半的数字

题目链接https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/

题目内容:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

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

示例 1:

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

题目解析

题目解析内容来自于题解中Krahets 和评论网友

题目的意思是简单明了的,给定一个数组,这个数组里面有一个数字出现此处超过数组总个数的一半。找到这个数。

方法一:python 导包

from collections import Counter

class Solution:
    def majorityElement(self, nums):
        res = Counter(nums)  // 获取的是 Counter 类
        return res.most_common(1)[0][0]  // most_common 列出前 n 个 元素 

Counter 可参考此。此方法时间复杂度,空间复杂度待补充

方法二:手动实现哈希表,即 python 字典

自己手动实习一个 python 字典。记录每个字符的数量,当统计某个字符的数量超过字符总数的一半,即可直接返回。

class Solution:
    def majorityElement(self, nums):
        if not nums:
            return None
        
        num_dict = dict()
        max_count, max_num = len(nums), nums[0]
        
        for num in nums:
            if num in num_dict:
                num_dict[num] += 1
            else:
                num_dict[num] = 1
            
            if num_dict[num] > max_count:
                max_count = num_dict[num]
                max_num = num
        return max_num
复杂度分析

方法三:数组排序法

将数组排序,由于众数的特性,即本题目中众数的数量超过总数量的一半,因此 数组中要求的数字一定是众数,且其在排序后的数组中一定在数组的中间

class Solution:
    def majorityElement(self, nums):
        if not nums:
            return
        sorted(nums)
        return nums[len(nums)//2]
复杂度分析

方法四:摩尔投票法

核心理念为"正负抵消;是本题的最佳解法

解释

技术图片

算法原理:

算法流程

  1. 初始化: 票数统计 votes = 0, 众数为 x

  2. 循环抵消:遍历数组 nums 中的每个数字 num;

    1. 当票数 votes 等于 0,即假设当前数字 num 为众数 x;
    2. 当 num = x 时,票数 votes 自增 1; 否则,票数 votes 自减 1
  3. 返回值:返回众数 x 即可

复杂度分析:

class Solution:
    def majorityElement(self, nums):
        votes = 0
        for num in nums:
            if votes == 0:
                x = num
            votes += 1 if num == x else -1
        return x

题目拓展:

class Solution:
    def majorityElement(self, nums):
        votes, count = 0, 0
        for num in nums:
            if votes == 0:
                x = num
            votes += 1 if num == x else -1
        
        # 验证 x 是否为众数
        for num in nums:
            if num == x:
                count += 1
        return x if count > len(nums) // 2 else 0   # 当无众数时返回 0
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!