先存着,c语言真就啥都没有呗
struct hashTable {
int key;
UT_hash_handle hh;
};
bool containsDuplicate(int* nums, int numsSize) {
struct hashTable* set = NULL;
for (int i = 0; i < numsSize; i++) {
struct hashTable* tmp;
HASH_FIND_INT(set, nums + i, tmp);
if (tmp == NULL) {
tmp = malloc(sizeof(struct hashTable));
tmp->key = nums[i];
HASH_ADD_INT(set, key, tmp);
} else {
return true;
}
}
return false;
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/contains-duplicate/solution/cun-zai-zhong-fu-yuan-su-by-leetcode-sol-iedd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
实现hashtable,大概写了下int类型的,,大概思路就是一个指针p指向一块内存,
这块内存有若干指针,分别指向一个链表,链表在hash碰撞的时候增加节点,牺牲内存增加速度
#include#include #define max_len 50 #define GET_KEY(num) (num)%max_len typedef struct hashnode { struct hashnode* next; int value; int count; }Hashnode; void init(Hashnode** hashtable, int size); void display(Hashnode** hashtable, int size); void find(Hashnode** hashtable, int size, int num); void test_null(Hashnode* p); void main() { int num[max_len * 2]; for (int i = 0; i < max_len * 2; i++) { num[i] = i + max_len; printf("%d ", num[i]); } printf("n"); Hashnode** hashtable = (Hashnode**)malloc(max_len * 8 + 8); test_null(hashtable); init(hashtable, max_len); num[98] = 50; for (int i = 0; i < max_len * 2; i++) { find(hashtable, max_len, num[i]); } display(hashtable, max_len); } void init(Hashnode** hashtable, int size) { Hashnode** p = hashtable; for (int i = 0; i < size; i++) {; (*p)= (Hashnode*)malloc(16); test_null(*p); (*p)->next = NULL; (*p)->value = -1; (*p)->count = 0; p++; } } void display(Hashnode** hashtable, int size) { for (int i = 0; i < size; i++) { Hashnode* p = *(hashtable + i); while (p) { printf("%d %d ", p->value, p->count); p = p->next; } printf("n"); } printf("nn"); } void find(Hashnode** hashtable, int size,int num) { int pos = GET_KEY(num),flag=0; Hashnode* p = *(hashtable + pos),*q=p; while (p) { if (p->value == -1) { p->value = num; p->count++; flag = 1; break; } if (p->value == num) { p->count++; flag = 1; break; } else { q = p; p = p->next; } } if (!flag) { Hashnode* node = (Hashnode*)malloc(16); test_null(node); node->value = num; node->next = NULL; node->count = 1; q->next = node; } } //vs还是会有没检查内存的警告,不知道是这么写有问题还是vs检查不到 void test_null(Hashnode* p) { if (!p) { printf("errorn"); exit(1); } }



