权值计算 码蹄集

题目来源:码蹄集

题目描述:

在这里插入图片描述
在这里插入图片描述

大致思路:

题意很好理解,就是看某个数字的出现次数是否大于等于它本身的值,返回符合这个条件的数中最大的一个。

使用字典统计每个数字出现的次数。具体地说,使用一个空字典 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Magneto_万磁王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值