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

问题

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

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

示例

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

解答1:排序

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return nums[nums.size() / 2];
    }
};

重点思路

排序后数组的中位数一定是出现次数超过一半的数。

解答2:哈希表

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int, int> ump;
        for (int i : nums)
            if (++ump[i] > nums.size() / 2) return i;
        return -1;
    }
};

解答3:摩尔投票法

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candi = 0, cnt = 0;
        for (int i : nums) {
            if (!cnt) candi = i;
            if (candi == i) cnt++;
            else cnt--;
        }
        return candi;
    }
};

重点思路

相同的增加,不同的抵消,最后肯定是出现次数超过半数的留下来。

posted @ 2021-03-03 20:04  tmpUser  阅读(29)  评论(0编辑  收藏  举报