c - “由于超时而终止”。需要帮助优化我的代码

标签 c arrays dictionary

我正在尝试实现字典。如果您发现我的代码中的缺陷而不是更改整个逻辑,我将不胜感激。

示例输入
3
萨姆99912222
汤姆11122222
哈利12299933
萨姆
爱德华
哈利

示例输出:
萨姆=99912222
未找到
哈里=12299933

#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));

关于c - “由于超时而终止”。需要帮助优化我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38183663/

相关文章:

arrays - 如何在 SCSS 中获取数组的 $values?

c - 使 fgets 不打印由箭头键或其他控制键引起的 ^G 或 ^D 之类的东西

arrays - 使用自定义范围过滤 [[String]]

Javascript 数组查找替代方案

javascript - 如何访问 map 内的下一个/上一个对象 - react ?

python - 将 Bottle FORMSDICT 转换为 Python 字典(以线程安全的方式)

python - 包含键中项目的字典中所有值的总和

c - while ((c = getchar()) != EOF) 不终止

c - 获取Gcov的执行行信息的顺序

c - 简单 C 程序的意外输出