• 【hdoj】哈希表题hdoj1425


    hdoj1425

    github链接

    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int offset = 500000;
    bool hash[offset+500001]; 
    
    
    int main()
    {
        int m, n;
        while(scanf("%d%d", &m, &n)!=EOF)
        {
            memset(hash, false, sizeof(hash));
            for(int i=0; i<m; i++){
                int num;
                scanf("%d", &num);
                hash[offset+num] = true;
            }
            for(int i=offset+500001; i>=0&&n>0; i--)
            {
                if(hash[i])
                {
                    if(n==1)
                        printf("%d
    ", i-offset);
                    else
                        printf("%d ", i-offset);
                    n--;
                }
            }
        }
        return 0;
     } 

    这道题数据是有范围的。我们可以将数据和存储位置做一个对应。

    做法是:当数字num存在时,将hash数组下标为num的值设为true。

    这样存储完毕后,就排序完成了。

     拓展:如果原题中“第二行包含n个各不相同”这一条件去掉,现在允许相同,那么该怎么编写?

    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int offset = 500000;
    int hash[offset+500001]; 
    
    
    int main()
    {
        int m, n;
        while(scanf("%d%d", &m, &n)!=EOF)
        {
            memset(hash, 0, sizeof(hash));
            for(int i=0; i<m; i++){
                int num;
                scanf("%d", &num);
                hash[offset+num]++;
            }
            for(int i=offset+500001; i>=0&&n>0; i--)
            {
                while(hash[i]>0&&n>0)
                {
                    if(n==1){
                        printf("%d
    ", i-offset);
                        n = 0;
                    }
                    else{
                        printf("%d ", i-offset);
                        n--;
                        hash[i]--;
                    }    
                }
            }
        }
        return 0;
     } 
    View Code
  • 相关阅读:
    vue项目中使用定时器,离开页面时清除定时器
    不能在循环中使用res.send(err);
    React使用require加载图片失败
    实验五 单元测试
    实验四 代码评审
    UML 建模工具的安装与使用
    结对编程 第二阶段
    结对编程
    GIT 代码版本管理
    结构化方法与面向对象化方法的比较
  • 原文地址:https://www.cnblogs.com/pusidun/p/8573090.html
Copyright © 2020-2023  润新知