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

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

题目

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

分析 & 解

  • dict方法:

    # -*- coding:utf-8 -*-
    class Solution:
        def MoreThanHalfNum_Solution(self, numbers):
            # write code here
            numsCount = {}
            numLen = len(numbers)
            for num in numbers:
                if num in numsCount:
                    numsCount[num] += 1
                else:
                    numsCount[num] = 1
                if numsCount[num] > (numLen>>1):
                    return num
            return 0
            
    

    时间复杂度和空间复杂度都是O(n)

  • 如果有大于一半的数字,那么两两不等则抵消掉,最后剩下的即有可能是那个大于一半的数字。空间复杂度为O(1):

    # -*- coding:utf-8 -*-
    class Solution:
        def MoreThanHalfNum_Solution(self, numbers):
            # write code here
            last = 0
            lastCount = 0
            
            for num in numbers:
                if lastCount == 0:
                    last = num
                    lastCount = 1
                else:
                    if num == last:
                        lastCount += 1
                    else:
                        lastCount -= 1
                        
            if lastCount == 0:
                return 0
            else:
                lastCount = 0
                for num in numbers:
                    if num == last:
                        lastCount += 1
                if lastCount > (len(numbers)>>1):
                    return last
            return 0
    

牛客网该题链接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章