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

地址  https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/

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

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


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

限制:
1 <= 数组长度 <= 50000

解答

1  使用哈希表记录每个元素出现的次数 找到出现最多的或者出现一半以上的就是我们要求的答案

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

 

2 众数如果存在则排序后的中间索引的数字一定是该数值,因为众数要是数组中一半以上的数值,

那么距离中间所以最远的位置就是开头和结尾,从开头和结尾计算一半以上的索引位置一定包括中间索引的位置,那么距离中间索引更近距离的位置必然也是如此

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

 

posted on 2021-02-18 23:03  itdef  阅读(70)  评论(0编辑  收藏  举报

导航