用C语言实现下述操作。有n个数(1<=n<=200000),第i个数为ai(1<=ai<=1000000000),求出这n个数中出现次数最多的数,并输出最多次数。
时间: 2024-05-09 17:15:05 浏览: 20
可以使用桶排序来实现该操作,先遍历一遍数组,将每个数出现的次数记录在桶中。然后再遍历一遍桶,找到出现次数最多的数以及其出现的次数。
以下是代码实现:
```c
#include <stdio.h>
int main()
{
int n, max_num = 0, max_count = 0;
scanf("%d", &n);
// 初始化桶
int bucket[1000000001] = {0};
// 遍历数组,统计每个数出现的次数
for (int i = 0; i < n; i++) {
int num;
scanf("%d", &num);
bucket[num]++;
}
// 遍历桶,找到出现次数最多的数
for (int i = 0; i < 1000000001; i++) {
if (bucket[i] > max_count) {
max_count = bucket[i];
max_num = i;
}
}
printf("%d %d", max_num, max_count);
return 0;
}
```
相关问题
C语言在键盘输入一个整数n(9800&<=n<=100000),统计1至n范围内素数的个数
你可以使用以下代码来实现:
```c
#include <stdio.h>
int is_prime(int num);
int main() {
int n, count = 0;
printf("请输入一个整数n(9800<=n<=100000):");
scanf("%d", &n);
for (int i = 2; i <= n; i++) {
if (is_prime(i)) {
count++;
}
}
printf("1至%d范围内素数的个数为%d", n, count);
return 0;
}
int is_prime(int num) {
if (num <= 1) {
return 0;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
```
首先,定义一个`is_prime()`函数,用于判断一个数是否为素数。然后,在主函数中,使用循环计算1至n范围内素数的个数,并输出结果。
对n(<=40)个整数进行升序排序。用C语言实现代码
可以使用冒泡排序、插入排序、选择排序等多种算法来实现升序排序。以下是冒泡排序的C语言实现代码示例:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)