HDU1029(去掉两个不同的数序列中出现频率最多的那个数不变)DP2

  1. 题目链接
  2. 题目要求:找出一个序列中出现频率大于(n+1)/2的那个数字
  3. AC代码
/*第一种方法就是对于一个序列来说
如果我们每次去掉两个不同的数,该序列中
出现频率最多的那个数是不变的
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
        int n;
        while(~scanf("%d",&n))
        {
                int cnt=0,res;
                for(int i=0;i<n;i++)
                {
                        int x;
                        scanf("%d",&x);
                        if(cnt==0)
                        {
                                res=x;
                                cnt++;
                        }
                        else
                        {
                                if(res==x)
                                cnt++;
                                else
                                cnt--;
                        }

                }
                printf("%d\n",res);
        }
        return 0;
}
/*第二种方法就是排序,
找出数组中出现次数超过一半的元素
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e8+5;
int a[maxn];
int main()
{
        int n;
        while(~scanf("%d",&n))
        {
                for(int i=0;i<n;i++)
                scanf("%d",&a[i]);
                sort(a,a+n);
                printf("%d\n",a[(n+1)/2]);
        }
        return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值