try 用HashSet解决C中的217. Contains Duplicate问题.
在我试图使计算出的指数始终为(+)后,我得到了一个错误.
#define BUCKET_SIZE 1000
typedef struct ListNodes {
int val;
struct ListNodes* next;
} ListNode;
typedef struct {
ListNode* buckets[BUCKET_SIZE];
} MyHashSet;
// create hash table
MyHashSet* myHashSetCreate() {
MyHashSet* obj = (MyHashSet*) malloc(sizeof(MyHashSet));
f或(int i = 0 ; i < BUCKET_SIZE ; i++ ) {
obj -> buckets[i] = NULL;
}
return obj;
}
bool myHashSet(MyHashSet* obj, int key) {
unsigned int index = key % BUCKET_SIZE; // problem here
ListNode* current = obj->buckets[index];
while(current != NULL) {
if(current -> val == key) return true;
current = current -> next;
}
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = key;
newNode->next = obj->buckets[index];
obj->buckets[index] = newNode;
return false;
}
// task function
bool containsDuplicate(int* nums, int numsSize) {
MyHashSet* obj = myHashSetCreate();
f或(int i = 0 ; i < numsSize ; i++) {
if(myHashSet(obj, nums[i])) {
return true;
}
}
return false;
}
unsigned int index = key % BUCKET_SIZE;
结果:
第23行:Char 15:运行时错误:加载地址0x6258000078f0,但空间不足,无法容纳类型为"struct ListNode *"的对象[solution.c] 0x 6258000078 f0:注:指针指向此处
ListNode* current = obj->buckets[index];
我通过以下方式修复了这个错误:
int index = key % BUCKET_SIZE;
或
int index = key % BUCKET_SIZE;
if( index < 0) {
index *= -1;
}
知道为什么代码的行为很奇怪吗?