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;
    }

知道为什么代码的行为很奇怪吗?

推荐答案

避免signed个数学:

bool myHashSet(MyHashSet* obj, int key) {
    unsigned int index =  key % BUCKET_SIZE;

改变

bool myHashSet(MyHashSet* obj, unsigned key) {
    unsigned int index =  key % BUCKET_SIZE;
// or 
bool myHashSet(MyHashSet* obj, int key) {
    unsigned int index =  (unsigned) key % BUCKET_SIZE;
// or 
// #define BUCKET_SIZE 1000
#define BUCKET_SIZE 1000u
// or ...

使用原始的unsigned int index = key % BUCKET_SIZE;key % BUCKET_SIZE计算出remainder,该remainder在-999到999之间. 将负值转换为unsigned,即为large unsigned个值.

C++相关问答推荐

在严格的C89模式下,收件箱不会在' uint64_t '上发出警告

为什么海湾合作委员会在共享对象中的. init_data的虚拟内存地址之前留出一个空白

为什么静态说明符为内联函数生成外部定义?

为什么PLT表中没有push指令?

为什么在C中设置文件的位置并写入文件,填充空字符?

getchar读css + z还是返回css?

如何将字符串argv[]赋给C中的整型数组?

创建一个fork导致fget无限地重新读取文件

使用C时,Windows CMD中的argc参数是否包含重定向命令?

如何按顺序将所有CSV文件数据读入 struct 数组?

如何仅使用软件重新初始化STM32微控制器中的USB枚举?

仅从限制指针参数声明推断非混叠

使用Open62541向OPCUA服务器发送读请求时内存泄漏

C语言中奇怪的输出打印数组

Realloc():中止的下一个大小无效(核心转储)

*S=0;正在优化中.可能是GCC 13号虫?或者是一些不明确的行为?

即使我在C++中空闲,也肯定会丢失内存

C: NULL>;NULL总是false?

共享内存未授予父进程权限

clion.我无法理解 Clion 中发生的 scanf 错误