【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
原文地址:https://www.cnblogs.com/pusidun/p/8573090.html