bit 1006 The most frequent number

本文介绍了一个算法问题:如何从一组整数中找出出现频率最高的数。通过排序和遍历的方法,实现了高效的查找,并展示了完整的C语言实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The most frequent number

时间限制: 1秒  内存限制: 64M

Problem Description

Given n integers, can you find the most frequent one? Now let’s think about this problem.

Input

This problem contains multiple test cases.

For each test case, the first line is an integer n (1 <= n <= 100000), then the next line has n integers, every of which is between -10^9 to 10^9.

The input is ended by EOF.

Output

For each test case, please output the most frequent number. If there is more than one solution, please output the minimum one.

Sample Input

6

1 2 2 2 3 5

3

-1 -1 -1

Sample Output

2

-1


排一次序,遍历一遍。ac。

#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a,const void *b){
	return (*(int *)a) - (*(int *)b);
}
int main(int argc, char *argv[])
{
	int a[100100]; 
	int n;
	int tem,tem_befor;
	int max,max_befor;
	//FILE *fp;
	//fp = freopen("in.txt","r",stdin);

	while(~scanf("%d",&n)){
		for(int i = 0;i < n;++i){
			scanf("%d",&a[i]);
		}
		qsort(a,n,sizeof(int),cmp);
		tem = a[0];
		tem_befor = a[0];
		max = 1;
		max_befor = 0;
		
		for(int i = 1; i < n;++i){
			if(tem == a[i]){
				++max;
			}else{
				if(max > max_befor){
					max_befor = max;
					tem_befor = tem;
					
				}
				tem = a[i];
				max = 1;
			}
		}
		printf("%d\n",max > max_befor ? tem:tem_befor);
		
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值