pre
1. 题目要求
2. 解答
2.1 结构体排序写法
因为数字范围有限,可以采用一个计数数组来存储每一个数,每个数组元素包含两部分,代表的数字以及代表的数字出现的次数。最后对这个数组进行排序,找到符合要求的一项即可。
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10010;
struct Elem {
int a;
int b;
bool operator< (const Elem& e) const
{
if(b != e.b) return b > e.b;
return a < e.a;
}
} nums[N];
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < N; i ++) {
nums[i]= {i, 0};
}
int a;
while(n--) {
scanf("%d", &a);
nums[a].b ++;
}
sort(nums, nums + N);
printf("%d", nums[0].a);
return 0;
}
因为用了一次 sort
排序,时间复杂度在
O
(
n
log
n
)
O(n\log{n})
O(nlogn)
2.2 计数数组遍历写法
这种办法更加简单,进一步降低了时间复杂度和空间复杂度(最差 O ( N ) O(N) O(N) 一般 O ( n ) O(n) O(n)):
#include <iostream>
using namespace std;
const int N = 10010;
int nums[N];
int main()
{
int n;
scanf("%d", &n);
int a;
while(n --) {
scanf("%d", &a);
nums[a] ++;
}
int res = -1;
int curr = 0;
for(int i = 0; i < N; i ++) {
if(nums[i] > res) {
res = nums[i];
curr = i;
}
}
printf("%d", curr);
return 0;
}
3. 总结
如果这一题要用结构体排序,sort
对结构体排序要会使用,也要记住 sort
对结构体进行排序的方式 (重载小于号,或者写 cmp
函数 )因为数据规模
n
n
n 在
10000
10000
10000 左右所以
O
(
n
log
n
)
O(n\log{n})
O(nlogn) 的算法可以接受。