NowCoder 频繁元素



题意及思路

  • 题意:找到出现次数最多的数,若有次数相同的就输出第一个出现的。
  • 思路:😊主要思想是,迭代执行!将n个数的值存入p数组,🙂每次将 p[x]的数所对应的cnt数组中位置增一(cnt为记录p数组元素出现的次数)。😄然后,比较max与cnt [ p[x] ]的大小,max小的话就更新max数据操作。
  • 思想:迭代更新!

代码

#include <bits/stdc++.h>
 
using namespace std;
 
int main(){
    int p[150],cnt[300],n;
    memset(cnt,0,sizeof(cnt));
    cin >> n;
    for(int i=0;i<n;i++) cin >> p[i];
    int max = -1,ans = 0;
    for(int i=0;i<n;i++){
        cnt[p[i]]++;
        if(cnt[p[i]]>max){
            max = cnt[p[i]];
            ans = p[i];
        }
    }
    cout << ans << endl;
    return 0;
}


全部评论

相关推荐

点赞 评论 收藏
分享
爱吃烤肠的牛油最喜欢...:50K是ssp了估计,ssp的人家多厉害都不用说,每年比例大概在百分之5左右
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务