其他算法-028-数组中出现次数超过一半的数字

文章目录

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

分析

  • 方法一:利用python字典,记录每个出现的数字的counter,再遍历得到结果,时间复杂度为O(n),空间复杂度为O(n)。并且此方法可以扩展成数组中有一个数字出现的次数超过任意次

  • 方法二:数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现次数的和还要多。因此我们可以考虑在遍历数组的时候保存两个值:一个是数组中的一个数字,一个是次数。

    • 当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1;
    • 如果下一个数字和我们之前保存的数字不同,则次数减1。
    • 如果次数为零,我们需要保存下一个数字,并把次数设为1。

代码

  • 方法一:
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        dictH = {}
        length = len(numbers)
        for i in numbers:
            if i in dictH:
                dictH[i] += 1
            else:
                dictH[i] = 1
        
        for i in set(numbers):
            if dictH[i] > length/2:
                return i
        
        return 0
  • 方法二:
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        if not numbers:
            return 0
        
        
        res = numbers[0]
        counter = 1
        length = len(numbers)
        
        
        for i in numbers[1:]:
            if i==res:
                counter += 1
            else:
                counter -= 1
                if counter == 0:
                    res = i
                    counter = 1
        
        if numbers.count(res)>length/2:
            return res
        return 0
发布了219 篇原创文章 · 获赞 85 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/z_feng12489/article/details/103476996