C语言 | Leetcode C语言题解之第347题前K个高频元素

题目:

题解:

cpp 复制代码
struct hash_table {
    int key;
    int val;
    // 查看 https://troydhanson.github.io/uthash/ 了解更多
    UT_hash_handle hh;
};

typedef struct hash_table* hash_ptr;

struct pair {
    int first;
    int second;
};

void swap(struct pair* a, struct pair* b) {
    struct pair t = *a;
    *a = *b, *b = t;
}

void sort(struct pair* v, int start, int end, int* ret, int* retSize, int k) {
    int picked = rand() % (end - start + 1) + start;
    swap(&v[picked], &v[start]);

    int pivot = v[start].second;
    int index = start;
    for (int i = start + 1; i <= end; i++) {
        // 使用双指针把不小于基准值的元素放到左边,
        // 小于基准值的元素放到右边
        if (v[i].second >= pivot) {
            swap(&v[index + 1], &v[i]);
            index++;
        }
    }
    swap(&v[start], &v[index]);

    if (k <= index - start) {
        // 前 k 大的值在左侧的子数组里
        sort(v, start, index - 1, ret, retSize, k);
    } else {
        // 前 k 大的值等于左侧的子数组全部元素
        // 加上右侧子数组中前 k - (index - start + 1) 大的值
        for (int i = start; i <= index; i++) {
            ret[(*retSize)++] = v[i].first;
        }
        if (k > index - start + 1) {
            sort(v, index + 1, end, ret, retSize, k - (index - start + 1));
        }
    }
}

int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
    hash_ptr head = NULL;
    hash_ptr p = NULL, tmp = NULL;

    // 获取每个数字出现次数
    for (int i = 0; i < numsSize; i++) {
        HASH_FIND_INT(head, &nums[i], p);
        if (p == NULL) {
            p = malloc(sizeof(struct hash_table));
            p->key = nums[i];
            p->val = 1;
            HASH_ADD_INT(head, key, p);
        } else {
            p->val++;
        }
    }
    struct pair values[numsSize];
    int valuesSize = 0;

    HASH_ITER(hh, head, p, tmp) {
        values[valuesSize].first = p->key;
        values[valuesSize++].second = p->val;
    }
    int* ret = malloc(sizeof(int) * k);
    *returnSize = 0;
    sort(values, 0, valuesSize - 1, ret, returnSize, k);
    return ret;
}
相关推荐
阿维的博客日记5 小时前
LeetCode 139. 单词拆分 - 动态规划解法详解
leetcode·动态规划·代理模式
程序员Xu6 小时前
【LeetCode热题100道笔记】二叉树的右视图
笔记·算法·leetcode
阿维的博客日记6 小时前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法
算法·leetcode
房开民7 小时前
使用海康机器人相机SDK实现基本参数配置(C语言示例)
c语言·数码相机·机器人
程序员Xu7 小时前
【LeetCode热题100道笔记】二叉搜索树中第 K 小的元素
笔记·算法·leetcode
Tina表姐8 小时前
(C题|NIPT 的时点选择与胎儿的异常判定)2025年高教杯全国大学生数学建模国赛解题思路|完整代码论文集合
c语言·开发语言·数学建模
金古圣人9 小时前
hot100 滑动窗口
数据结构·c++·算法·leetcode·哈希算法
高山有多高10 小时前
详解文件操作
c语言·开发语言·数据库·c++·算法
YuTaoShao10 小时前
【LeetCode 热题 100】49. 字母异位词分组
算法·leetcode·哈希算法
程序员Xu12 小时前
【LeetCode热题100道笔记】腐烂的橘子
笔记·算法·leetcode