leetcode169. 求众数(map的用法、摩尔投票法)

题目描述:

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

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

示例:

输入:[2, 2, 1, 1, 1, 2, 2]

输出:2

方法一:建立map来记录数组中每个不重复元素的出现次数,然后遍历map,查找map中value大于n/2的key值,该值即为众数。

#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;

class Solution{
public:
    int majorityElement(vector<int>& nums){
        map<int, int> mapElement;   //初始化一个map,其中key表示数组中不重复的元素,value表示该元素在数组中出现的次数 
        int element;
        for(int i=0; i<nums.size();++i){
            if(mapElement.count(nums[i]) == 0) //查找map中是否包含该元素,若为0,则不包含 
                mapElement.insert(make_pair(nums[i], 1));
            else
                mapElement[nums[i]] += 1;    
        }
        map<int, int>::iterator it = mapElement.begin();
        while(it != mapElement.end()){
            if(it->second > nums.size()/2){
                element = it->first;
                break;
            }
            it++;
        }
        return element; 
    }
};

int main(){
    Solution solution;
    vector<int> vec;
    int i;
    do{
        cin>>i;
        vec.push_back(i);
    }while(getchar() != '\n');
    int res;
    res = solution.majorityElement(vec);
    cout<<res<<endl;
    return 0;
}

 

方法二:由于数组中众数一定是数组中出现次数大于n/2的元素,所以我们将数组排序后,位于数组中间的那个元素一定是众数。

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

方法三:由于众数是出现次数大于n/2的元素,设置数组中第一个元素为众数,count为1。从第二个元素开始遍历数组,若元素与众数相等,则count+1,若不等,则count-1。当count变为0时,我们更新众数为下一个元素,count重新置为1.数组遍历完成得到的众数即为所求众数。

上述方法又称为摩尔投票法,即查找输入中重复出现超过一半以上(n/2)的元素。摩尔投票的思想:在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除,这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组的一半。如果只存在一种元素,则这个元素即为目标元素。

class Solution{
public:
    int majorityElement(vector<int>& nums){
        int element = nums[0];
        int count = 1;
        for(int i=1; i<nums.size(); ++i){
            if(nums[i] == element)
                count++;
            else
                count--;
            if(count == 0){
                element = nums[++i];
                count++;
            }
        }
        return element;
    }
};

 

转载于:https://www.cnblogs.com/jiangyaju/p/11044917.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值