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;
}
相关推荐
爱编码的小八嘎39 分钟前
C语言完美演绎7-5
c语言
x_xbx1 小时前
LeetCode:438. 找到字符串中所有字母异位词
算法·leetcode·职场和发展
REDcker1 小时前
OpenSSL:C 语言 TLS 客户端完整示例
c语言·网络·数据库
派大星~课堂2 小时前
【力扣-94.二叉树的中序遍历】Python笔记
笔记·python·leetcode
AI成长日志2 小时前
【笔面试算法学习专栏】堆与优先队列实战:力扣hot100之215.数组中的第K个最大元素、347.前K个高频元素
学习·算法·leetcode
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 45. 跳跃游戏 II | C++ 贪心算法最优解题解
c++·leetcode·游戏
北顾笙9802 小时前
day18-数据结构力扣
数据结构·算法·leetcode
阿Y加油吧2 小时前
LeetCode 中等难度 | 回溯法进阶题解:单词搜索 & 分割回文串
算法·leetcode·职场和发展
float_com3 小时前
LeetCode 27. 移除元素
leetcode
quintin-lee3 小时前
Postgres 内核:从入门到“入土” (三) —— Page 结构:数据是如何在磁盘上“躺平”的
c语言·数据库·postgresql·数据库架构