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

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

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

示例 1:

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

这个题目有三种方法
1)用hashmap记录每个数字出现的次数,时空复杂度为O(n)
2)排序,中位数
3)摩尔投票法,相抵消

摩尔投票抵消:
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = 0, ans = 0;
        for (int num : nums) {
            if (n == 0) {
                ans = num;
                n++;
            }
            else {
                if (num == ans)
                    n++;
                else
                    n--;
            }
        }
        return ans;
    }
};

 

posted on 2022-03-08 09:48  4小旧  阅读(17)  评论(0)    收藏  举报

导航