我用C這樣做過。我想你會從代碼中理解我的想法。 (由nos注:這個算法被稱爲Trie)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node node;
struct node {
node *nodes[0x10];
char *text;
};
node *top;
void set(unsigned long long A, char *B)
{
unsigned char n;
node *way;
way = top;
for (;A>0;A>>=4)
{
n = A & 0xf;
if (way->nodes[n] == NULL)
{
way->nodes[n] = malloc(sizeof(node));
memset(way->nodes[n], 0, sizeof(node));
}
way = way->nodes[n];
}
if (way->text != NULL)
{
free(way->text);
}
way->text = strdup(B);
}
char *get(unsigned long long A)
{
unsigned char n;
node *way;
way = top;
for (; A>0 && way != NULL; A>>=4)
{
n = A & 0xf;
way = way->nodes[n];
}
if (A == 0 && way != NULL)
{
return way->text;
}
return NULL;
}
int main()
{
top = malloc(sizeof(node));
memset(top,0,sizeof(node));
set(1230294381243, "test1");
set(12934839, "test2");
set(1,"tezt");
printf("%s", get(1230294381243));
printf("%s", get(12934839));
printf("%s", get(1));
// todo: free memory
// free_way(top);
return 0;
}
最大16次迭代找到任何unsigned long long
鍵。此代碼是100%正常工作並進行了測試,但從top
變量中釋放內存除外。
UPDATE。聲明node
s作爲數組(建議HolyBlackCat)。
UPDATE。提高算法速度(建議Serge Rogatch)
你的答案是什麼? –
'O(1)'認爲哈希。 – PaulMcKenzie
如果您知道哈希表使用哈希函數,這是一個簡單的答案。 'set()'將鍵值設置爲'A'作爲鍵,'B'作爲值,Get將使用鍵'A'獲取'get()'值'B' ...出於好奇,你能說出什麼公司這是爲了什麼? –