剑指offer

面试题39. 数组中出现次数超过一半的数字

2020-03-20  本文已影响0人  人一己千

题目

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

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

示例 1:

<pre style="box-sizing: border-box; font-size: 13px; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: rgb(247, 249, 250); padding: 10px 15px; color: rgb(38, 50, 56); line-height: 1.6; border-radius: 3px; white-space: pre-wrap;">输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2</pre>

限制:

1 <= 数组长度 <= 50000

注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/

解法

采用投票方法,超过半数的票和其他票相抵消的话,最后剩下的一定是超过半数的。

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count = 0
        num = nums[0]
        for i in nums:
            if count == 0:
                num = i
                count += 1
            elif i == num: count +=1
            else: count -= 1
        return num

总结

在count为0的时候,不要忘记了num+1.

上一篇下一篇

猜你喜欢

热点阅读