剑指 Offer 39. 数组中出现次数超过一半的数字

剑指 Offer 39. 数组中出现次数超过一半的数字

题目

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

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

思路

方法一:哈希表

通过一个 hashmap 记录每个数的个数,如果大于一半就输出。

方法二:排序

排序,然后最中间的数就是次数超过数组长度一半的数

方法三:Boyer-Moore 投票算法

核心就是票数相抵,超过一半的肯定会留到最后

知乎上面看到的一种回答

https://www.zhihu.com/question/49973163/answer/617122734

代码

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = -1;
        int count = 0;
        for (int num : nums) {
            if (candidate == num) {
                ++count;
            } else if (--count < 0) {
                candidate = num;
                count = 1;
            }
        }
        return candidate;
    }
};
posted @ 2022-04-14 16:32  沐灵_hh  阅读(16)  评论(0编辑  收藏  举报