众数

题目描述

输入20个数,每个数都在1-10之间,求1-10中的众数(众数就是出现次数最多的数,如果存在一样多次数的众数,则输出权值较小的那一个)。

输入描述:

测试数据有多组,每组输入20个1-10之间的数。

输出描述:

对于每组输入,请输出1-10中的众数。

分析

用一个数组count[11]来统计每个数出现的次数

for(int i = 0; i < 20; i++){
      count[a[i]]++;
}
#include <iostream>
using namespace std;

int main(){
    int a[20];
    int count[11];
    
    while(cin >> a[0]){
        for(int i = 1; i < 20; i++){
            cin >> a[i];
        }
        for(int i = 1; i < 11; i++){
            count[i] = 0;
        }
        for(int i = 0; i < 20; i++){
            count[a[i]]++;
        }
        int max = count[1];
        int index = 1;
        for(int i = 2; i < 11; i++){
            if(count[i] > max){
                max = count[i];
                index = i;
            }
        }
        cout << index << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhuobo/p/10206582.html