C “由于超时而终止”。需要帮助优化我的代码吗
我正在努力实现字典。如果您能在我的代码中找到缺陷,而不是改变整个逻辑,我将不胜感激 样本输入 3. 山姆99912222 汤姆11122222 哈里12299933 山姆 爱德华 哈利 样本输出: sam=99912222 找不到 harry=12299933C “由于超时而终止”。需要帮助优化我的代码吗,c,arrays,dictionary,C,Arrays,Dictionary,我正在努力实现字典。如果您能在我的代码中找到缺陷,而不是改变整个逻辑,我将不胜感激 样本输入 3. 山姆99912222 汤姆11122222 哈里12299933 山姆 爱德华 哈利 样本输出: sam=99912222 找不到 harry=12299933 #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> struct Dict { c
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
struct Dict {
char key[100];
int value;
};
struct Dict *array;
int inputsize;
int getHashKey(char *key){
return strlen(key)%inputsize;
}
void insert(char *key, int value){
int i =0;
int hashkey = getHashKey(key);
/* Already inserted. Return */
if(!strcmp (array[hashkey].key,key)){
return;
}
/* Check if empty space. else, Get the next available space. */
if(array[hashkey].value == 0){
strcpy(array[hashkey].key,key);
array[hashkey].value = value;
}else{
hashkey++;
while(array[hashkey].value!=0){
hashkey++;
/*if reached end of array. Re-start */
if(hashkey == inputsize ){
hashkey = 0;
}
}
strcpy(array[hashkey].key,key);
array[hashkey].value = value;
}
}
void search(char *key){
for(int i =0;i<inputsize;i++){
if(!strcmp(array[i].key,key)){
printf("%s=%d\n",array[i].key,array[i].value);
return;
}
}
printf("Not found\n");
}
int main() {
char key[100]; int value;
scanf("%d",&inputsize);
char *ptr[inputsize];
//Initializing array pointer
for(int i=0;i<inputsize;i++){
ptr[i] = (char *)malloc(sizeof(char) * 100);
}
array = (struct Dict *)malloc(sizeof(struct Dict)*inputsize);
/*Reading Input.Key & value pair */
for(int i=0;i<inputsize;i++){
scanf("\n%20[^ ]",key);
scanf("%d",&value);
insert(key,value);
}
/*Reading Query */
for(int i =0; i<inputsize;i++){
scanf("%s",ptr[i]);
}
/* Searching Query String in Dict */
for(int i =0;i<inputsize;i++){
search(ptr[i]);
}
return 0;
}
以下循环永远不会结束:
while (array[hashkey].value != 0) {
hashkey++;
/*if reached end of array. Re-start */
if (hashkey == inputsize) {
hashkey = 0;
}
}
你必须检查你的算法,让它正确地结束。
您可以做的第一件事是将数组归零,以确保在使用它之前正确初始化它。malloc只是在分配内存。它不会为您执行任何初始化
array = (struct Dict *)malloc(sizeof(struct Dict)*inputsize);
memset(array, 0, sizeof(sizeof(struct Dict)*inputsize));
您似乎正在构建哈希表,但在搜索时执行线性扫描。这意味着当使用线性哈希方案时,搜索是打开的,而不是接近O1。我假设由于超时而终止是来自某种在线判断。您是否在本地对其进行了测试,并验证了它在问题陈述中规定的限制范围内对样本输入和最大输入都有效?这不是性能问题。您忘记了初始化数组,因此程序不明确。这里没有C++。如果这是C,我们可以删除C++标签吗?如果它是C++,我们可以使用STL而不是自制程序吗?如果你的代码工作正常,我想你想问一下这个问题。不过,你可能想读一下他们的介绍性文章——我看到你为此跳过了这一步。请务必阅读他们的。在旁注中,我几乎可以肯定scanf\n%20[^],key;是一种错误的阅读方式…或者使用它不是永不停止的行为。然而,我需要一种方法来改变这种未定义的行为。我会限制的。我修正了这行代码。这并没有解决我的问题。顺便说一句,谢谢你提出这个问题。如果两个不同的情况下密钥相似,我正在尝试获得可用空间,所以在这种情况下搜索不能是O1。