c语言实现:
struct hash_table {
int key;
int value; // value 用不到
; /* makes this structure hashable */
UT_hash_handle hh};
// 必须要初始化为NULL,考虑到leetcode c语言实现执行多个用例时全局变量和静态变量只会初始化一次,
// 所以我们就不在这里初始化值,而是放到main()中,
// 防止以后从这里copy代码到leetcode中时用例不通过
static struct hash_table *head_table;
static void uthash_add(struct hash_table *add)
{
(head_table, key, add); // 这里的key不是变量,而是结构体成员名
HASH_ADD_INT}
static struct hash_table *uthash_find(int key)
{
struct hash_table *out;
(head_table, &key, out); // 这里的key是变量
HASH_FIND_INTreturn out;
}
static void uthash_delete(struct hash_table *del)
{
(head_table, del);
HASH_DEL}
bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
= NULL;
head_table struct hash_table *tmp;
struct hash_table *curr, *next;
for (int i = 0; i < numsSize; i++) {
if (i > k) {
// 窗口大小为k,移除掉一个元素
= uthash_find(nums[i - k - 1]);
tmp if (tmp)
(tmp);
uthash_delete}
= uthash_find(nums[i]);
tmp if (tmp)
return true;
= malloc(sizeof(struct hash_table));
tmp ->key = nums[i];
tmp// tmp->value 用不到
(tmp);
uthash_add}
(hh, head_table, curr, next) {
HASH_ITER(curr);
uthash_delete(curr);
free}
return false;
}