Solution Idea

50054. A Hash Table

解題流程為:
1:讀入字串並建立hash table,並記錄目前每個bucket已存幾筆資料。
2:讀入每筆query並計算該query的hash index。
3:到剛剛算出的index bucket中搜尋比對,若有在bucket中,則輸出該bucket的index;若沒有,則輸出-1。
*只需搜尋和query同樣index的bucket,切勿將整個table都搜尋一遍,否則花非常多的時間。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
char *hashTable[1000][10000];//at most 1000 buckets and each bucket has 10000 strings
int hashFunc(char *a, int length, int size)
{
    int key = 0;
    for (int i = 0; i < length; ++i)
    {
        if(isdigit(a[i]))
            key += a[i] - '0';
        else
            key += a[i];
    }
    return key % size;
}
 
int main(int argc, char const *argv[])
{
 
    char elements[10000][101];//at most 10000 strings
    int count[1000] = {0};//counter of bucket
 
    int S, N, Q;
    scanf("%d %d %d", &S, &N, &Q);
//build a hash table
    for(int i = 0; i < N; i++){
        scanf("%s", elements[i]);
        int length = strlen(elements[i]);
        elements[i][length] = '\0';
 
        int index = hashFunc(elements[i], length, S);//use hash function to get hash index
        hashTable[index][count[index]++] = elements[i];//store input string to hash table by index
    }
 //query
    for (int i = 0; i < Q; ++i)
    {
        char query[101];
        scanf("%s", query);
        int state = 0, index = hashFunc(query, strlen(query), S);//use hash function to get hash index
        for (int j = 0; j < count[index]; ++j)
        {  
            if(strcmp(hashTable[index][j], query) == 0){
                printf("%d\n", index);//if find out the query at that bucket then output bucket index
                state = 1;
                break;
            }
        }
        if(!state)//query is not exist in hash table
            printf("-1\n");//output -1
    }
 
    return 0;
}

Discussion