C语言 | Leetcode C语言题解之第219题存在重复元素II

题目:

题解:

cpp 复制代码
struct HashEntry {
    int key;                  
    int val;
    UT_hash_handle hh;         
};

void hashAddItem(struct HashEntry **obj, int key, int val) {
    struct HashEntry *pEntry;
    pEntry = malloc(sizeof(struct HashEntry));
    pEntry->key = key;
    pEntry->val = val;
    HASH_ADD_INT(*obj, key, pEntry);
} 

struct HashEntry *hashFindItem(const struct HashEntry **obj, int key)
{
    struct HashEntry *pEntry = NULL;
    HASH_FIND_INT(*obj, &key, pEntry);
    return pEntry;
}

void hashEraseItem(struct HashEntry **obj, int key)
{   
    struct HashEntry *pEntry = NULL;
    HASH_FIND_INT(*obj, &key, pEntry);
    if (NULL != pEntry) {
        HASH_DEL(*obj, pEntry);
        free(pEntry);
    } 
}

void hashFreeAll(struct HashEntry **obj)
{
    struct HashEntry *curr, *next;
    HASH_ITER(hh, *obj, curr, next)
    {
        HASH_DEL(*obj,curr);  
        free(curr);      
    }
}

bool containsNearbyDuplicate(int* nums, int numsSize, int k){
    struct HashEntry *cnt = NULL;
    for (int i = 0; i < numsSize; i++) {
        if (i > k) {
            hashEraseItem(&cnt, nums[i - k - 1]);
        }
        struct HashEntry * pEntry = hashFindItem(&cnt, nums[i]);
        if (NULL != pEntry) {
            return true;
        }
        hashAddItem(&cnt, nums[i], 1);
    }
    hashFreeAll(&cnt);
    return false;
}
相关推荐
YuTaoShao10 分钟前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
Heartoxx11 分钟前
c语言-指针(数组)练习2
c语言·数据结构·算法
杰克尼2 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode
YuTaoShao2 小时前
【LeetCode 热题 100】56. 合并区间——排序+遍历
java·算法·leetcode·职场和发展
JoJo_Way7 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
码农不惑8 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
凌肖战9 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
BreezeJuvenile10 小时前
数据结构与算法分析课设:一元多项式求值
c语言·课程设计·数据结构与算法分析·一元多项式计算
悲伤小伞11 小时前
linux_git的使用
linux·c语言·c++·git
GEEK零零七11 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列