首页 > 编程语言 > 详细

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

时间:2021-03-03 21:37:14      阅读:32      评论:0      收藏:0      [点我收藏+]

问题

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

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

示例

输入: [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, counter = 0;
        for (int i : nums) {
            if (!counter) {
                candi = i;
                counter = 1;
            } else {
                if (candi == i) counter++;
                else counter--;
            }
        }
        return candi;
    }
};

重点思路

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

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

原文:https://www.cnblogs.com/tmpUser/p/14476636.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!