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;
}
相关推荐
RuoZoe16 小时前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_4 天前
C语言内存函数
c语言·后端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
czy87874756 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237176 天前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll6 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐6 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶6 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode