问题描述
我在 Leetcode 上做一个 problem。它说我通过了我的第一个测试用例,但我的第二个测试用例失败了,答案很简单。当我手动运行那个案例时,我通过了,所以我知道这与它们运行之间的数据持久性有关。这显然是我正在使用的哈希表,我首先在全局声明了它。为了解决这个问题,我首先尝试使用 calloc 和 memset 将其重置为零,但出现了段错误。
我认为合乎逻辑的事情是在调用者函数内创建哈希,所以每次调用它时都会重新初始化。但是,即使它看起来应该可以工作,我仍然收到段错误错误(地址消毒剂致命信号)。我是否滥用指针?
这是我的代码不起作用。注释 //\ 代表我之前的代码行,它逐案工作。没有太多变化——主要是为了返回哈希。我评论了 seg 错误发生的位置(根据我的 printf 调试)。我希望我没有错过任何东西。我试图将两个编码实例合二为一,因为它大多是冗余的。
#define SIZE 1000
typedef struct htent{
struct htent* next;
int key,value;
} htent;
int hashf(int val,int size){
return val % SIZE; // don't need anything fancy
}
htent* create_new_htent(int val){ // the value is its own key
htent* ent = malloc(sizeof(htent));
ent->next = NULL;
ent->key = val;
ent->value = val;
return ent;
}
// htent* ht[SIZE] = {0}; //\\ This was my method before (main difference)
htent* build_hash_table_n_get_lowest(int* nums,int numsSize,int* low){ //\\ returned void before
htent* ht[SIZE] = {0}; //\\ before was commented out
int hash;
int running_low = 10000; // large #
htent* tmp;
for (int i = 0; i < numsSize; i++){
if (nums[i] < 1 ) continue; // drop negatives
if (nums[i] < running_low) running_low = nums[i];
printf("%d: Running Low %d\n",i,running_low);
htent* ent = create_new_htent(nums[i]);
hash = hashf(nums[i],numsSize);
if (ht[hash] == NULL){
ht[hash] = ent; // singly linked list
continue;
}
tmp = ht[hash];
while(tmp->next != NULL){
tmp = tmp->next;
}
tmp->next = ent;
}
*low = running_low;
return ht; //\\ was commented out before
}
int find_missing_lowest(htent** ht,int lowest){
int moving_target = 1;
for (int i = 0; i<numsSize; i++){
if (ht[moving_target] == NULL){ // SEG FAULTS HERE!!!
return moving_target;
}
moving_target++;
}
return moving_target;
}
int firstMissingPositive(int* nums,int numsSize){ // Function Leetcode calls
int lowest;
htent* ht = build_hash_table_n_get_lowest(nums,numsSize,&lowest); // tried with htent**
return find_missing_lowest(ht,lowest);
}
编辑:我使用全局作用域方法构建了这个函数,它可以工作并且这些测试通过(只需要处理边缘情况),但必须有更好的方法;
void refresh_hashtable(){
for (int i = 0; i<SIZE; i++){
ht[i] = NULL;
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)