zoukankan      html  css  js  c++  java
  • HDU1029 Ignatius and the Princess IV (水题)

    <题目链接>

    题目大意:
    给你一段序列,问你在这个序列中出现次数至少为 (n+1)/2 的数是哪个。

    解题分析:

    本题是一道水题,如果用map来做的话,就非常简单,但是另一个做法还比较巧妙。

    解法一:

    #include <cstdio>
    int main()
    {
        int n,t,cnt,result;
        while(scanf("%d",&n)!=EOF){
            cnt=0;
            for(int i=0;i<n;i++){
                scanf("%d",&t);           
                if(cnt==0){  //由于其它的所有数的出现次数都没它多,所以最后一定是这个特殊的数为result 
                    cnt=1;
                    result=t;
                }
                else{
                    if(t==result)cnt++;
                    else cnt--;
                }    
            }
            printf("%d
    ",result);    
        }  
        return 0;  
    }   

    map解法:

    #include <cstdio>
    #include <algorithm>
    #include <map>
    using namespace std;
    
    int main(){
        int n;
        while(scanf("%d",&n)!=EOF){
            map<int,int>mpa;
            for(int i=1;i<=n;i++){
                int x;scanf("%d",&x);
                mpa[x]++;
            }
            map<int,int>::iterator it;
            for(it=mpa.begin();it!=mpa.end();it++){
                if(it->second>=(n+1)/2){
                    printf("%d
    ",it->first);
                    break;
                }
            }
        }
        return 0;
    }

    2018-09-26

  • 相关阅读:
    python注释中文
    python学习好文
    浅析python 的import 模块(转)
    Python解释器镜像源修改
    Python解释器安装
    Python和Python解释器
    计算机基础小结
    网络瓶颈效应
    编程语言分类
    子查询|视图事务
  • 原文地址:https://www.cnblogs.com/00isok/p/9708414.html
Copyright © 2011-2022 走看看