美文网首页
数组中出现次数超过一半的数字

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

作者: 而立之年的技术控 | 来源:发表于2019-12-22 21:52 被阅读0次
    微信图片_20191222215040.jpg
    class Solution:
        def MoreThanHalfNum_Solution(self, numbers):
            # write code here
            if not numbers:
                return 0
            count = 0
            value = None
            for i in numbers:
                if value == None and count == 0:
                    value = i
                    count += 1
                if value != None and count > 0:
                    if value == i:
                        count += 1
                    else:
                        count -= 1
                        if count == 0:
                            value = None
            count2 = 0
            if value:
                for i in numbers:
                    if i == value:
                        count2 += 1
            if 2*count2 > len(numbers):
                return value
            else:
                return 0
    

    相关文章

      网友评论

          本文标题:数组中出现次数超过一半的数字

          本文链接:https://www.haomeiwen.com/subject/xslanctx.html