C语言 | Leetcode C语言题解之第220题存在重复元素III

题目:

题解:

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

int getID(int x, long long w) {
    return x < 0 ? (x + 1ll) / w - 1 : x / w;
}

struct HashTable* query(struct HashTable* hashTable, int x) {
    struct HashTable* tmp;
    HASH_FIND_INT(hashTable, &x, tmp);
    return tmp;
}

bool containsNearbyAlmostDuplicate(int* nums, int numsSize, int k, int t) {
    struct HashTable* hashTable = NULL;
    for (int i = 0; i < numsSize; i++) {
        long long x = nums[i];
        int id = getID(x, t + 1ll);
        struct HashTable* tmp;
        tmp = query(hashTable, id - 1);
        if (tmp != NULL && fabs(x - tmp->val) <= t) {
            return true;
        }
        tmp = query(hashTable, id + 1);
        if (tmp != NULL && fabs(x - tmp->val) <= t) {
            return true;
        }
        tmp = query(hashTable, id);
        if (tmp != NULL) {
            return true;
        } else {
            tmp = malloc(sizeof(struct HashTable));
            tmp->key = id;
            tmp->val = x;
            HASH_ADD_INT(hashTable, key, tmp);
        }
        if (i >= k) {
            tmp = query(hashTable, getID(nums[i - k], t + 1ll));
            HASH_DEL(hashTable, tmp);
        }
    }
    return false;
}
相关推荐
呆呆的小鳄鱼几秒前
如何刷新缓冲区(c++、c、linux)
linux·c语言·c++
W说编程1 小时前
算法导论第三章:数据结构艺术与高效实现
c语言·数据结构·算法
hn小菜鸡1 小时前
LeetCode 2529.正整数和负整数的最大计数
java·算法·leetcode
hn小菜鸡1 小时前
LeetCode 2917.找出数组中的K-or值
数据结构·算法·leetcode
Once_day2 小时前
代码训练LeetCode(34)文本左右对齐
算法·leetcode·c
is08152 小时前
C语言运行时
c语言·开发语言
zhuiQiuMX2 小时前
SQL力扣
数据库·sql·leetcode
Tess_Blingbling3 小时前
力扣Hoot100 第一天 | 哈希3题
leetcode·哈希算法·散列表
好易学·数据结构3 小时前
可视化图解算法51:寻找第K大(数组中的第K个最大的元素)
数据结构·python·算法·leetcode·力扣·牛客网·堆栈
电院工程师3 小时前
轻量级密码算法PRESENT的C语言实现(无第三方库)
c语言·算法·安全·密码学