首页 > 试题广场 >

找出出现次数最多的整数

[编程题]找出出现次数最多的整数
  • 热度指数:432 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个整数集合,集合中可能有重复的数字,输出其中出现次数最多的整数。
如果有多个整数,他们出现的次数相同,并且都是出现次数都是最多的,那么按照这些整数的大小排序,最终输出最大的那个整数。

输入描述:
整数集合,整数之间用空格分隔


输出描述:
出现次数最多的整数,如果有多个这样的整数,那么输出值最大的那个整数
示例1

输入

1 2 2 4 3 5 5 4 6 4

输出

4

说明

4出现次数最多,一共3次,所以输出4
示例2

输入

1 3 4 5 3 6 3 1 0 8 1

输出

3

说明

1和3都出现了3次,但是3比1大,所以最终输出3
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int num,max_cnt = INT_MIN;
    vector<int> nums;
    unordered_map<int,int> hash;
    while(cin >> num)
        hash[num]++;
    for(auto it = hash.begin();it != hash.end(); it++)
        max_cnt = max(it->second, max_cnt);
    for(auto it = hash.begin();it != hash.end(); it++)
         if(it->second == max_cnt)
             nums.push_back(it->first);
    sort(nums.begin(), nums.end(), greater<int>());
    cout << nums[0] << endl;
    return 0;
}
发表于 2022-03-15 22:26:28 回复(0)
遍历序列,搞个map存一下,维护最多序列,应该可以吧。。。。
发表于 2021-02-21 16:21:19 回复(0)