题目来源:码蹄集
题目描述:
大致思路:
题意很好理解,就是看某个数字的出现次数是否大于等于它本身的值,返回符合这个条件的数中最大的一个。
使用字典统计每个数字出现的次数。具体地说,使用一个空字典 cnt 来保存每个数字出现的次数,对于列表中的每个数字 x,检查它是否已经在字典 cnt 中出现过。如果没有出现,则将其初始值设为 0,否则将其出现次数加 1。
然后,检查当前数字 x 出现的次数是否大于等于 x 本身,如果是,则更新变量 res 为 x 和当前 res 中的最大值,这样就可以在遍历完整个列表后找到第一个出现次数不小于该数字本身的数字。
最后,输出结果 res,即可得到答案。
Python代码实现:
n = int(input())
cnt = {}
res = 0
for x in map(int, input().split()):
if x not in cnt:
cnt[x] = 0
cnt[x] += 1
if cnt[x] >= x:
res = max(res, x)
print(res)
C++代码实现:
参考链接:https://blog.51cto.com/u_15745546/5950610
#include<bits/stdc++.h>
using namespace std;
#define debug(x) cerr<< #x << " is "<<x<<endl;
typedef long long ll;
typedef pair<int,int> p;
const int INF=0x3f3f3f3f;
const int N=1e5+5;
int n;
unordered_map<int, int> cnt;
int main( )
{
cin>>n;
int res=0,x;
for(int i=1;i<=n;++i){
cin>>x;
cnt[x]++;
if(cnt[x]>=x) res=max(res,x);
}
cout<<res<<"\n";
return 0;
}
Java代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Map<Integer, Integer> cnt = new HashMap<>();
int res = 0;
for (int i = 1; i <= n; ++i) {
int x = in.nextInt();
if (!cnt.containsKey(x)) {
cnt.put(x, 0);
}
cnt.put(x, cnt.get(x) + 1);
if (cnt.get(x) >= x) {
res = Math.max(res, x);
}
}
System.out.println(res);
}
}
代码提交测试结果:
附B站老师思路讲解:https://www.bilibili.com/video/BV1Ua4y1V7qX/?t=1534.5