【求出现次数第二多的数】HDU-1347 Grandpa is Famous

在这里插入图片描述
在这里插入图片描述

注解

1、求出现次数第二多的数。先依次统计每个数出现的次数。然后求出第二多的出现次数是几。然后再遍历一遍,把出现次数等于这个数的所有数都求出来。

代码

#include <iostream>
#include <algorithm>

using namespace std;

const int maxn = 10001;

struct Num{
    int x;
    int cnt;
};

int compare(Num n1, Num n2){
    if(n1.cnt!=n2.cnt){
        return n1.cnt>n2.cnt;
    }
    else{
        return n1.x<n2.x;
    }
}

int main() {

    int N, M;
    cin>>N>>M;
    while(N || M){
        Num num[maxn];
        for(int i=0; i<maxn; i++){
            num[i].x = i;
            num[i].cnt = 0;
        }
        for(int i=0; i<N; i++){
            for(int j=0; j<M; j++){
                int t;
                cin>>t;
                num[t].cnt++;
            }
        }
        sort(num, num+maxn, compare);
        int mmax = num[0].cnt;
        int pos = -1;
        int secondmax = -1;
        for(int i=0; i<N; i++){
            if(num[i].cnt<mmax){
                pos = i;
                secondmax = num[i].cnt;
                break;
            }
        }
        cout<<num[pos].x;
        for(int i=pos+1; i<maxn; i++){
            if(num[i].cnt==secondmax){
                cout<<" "<<num[i].x;
            }
        }
        cout<<endl;
        cin>>N>>M;
    }

    return 0;
}

结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值