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;
}
相关推荐
圣保罗的大教堂2 分钟前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
码不停蹄Zzz40 分钟前
指针用法篇——malloc和free指针详解
c语言
彧azz1 小时前
操作系统时间管理与系统核心板块学习总结
c语言·笔记·学习·系统架构
白色的北极熊1 小时前
c语言 牛客网 BC15
c语言
Tim_101 小时前
【LeetCode】338、比特位计数
c++·算法·leetcode
老当益壮梁奶奶2 小时前
ARM汇编学习笔记(六):【i.MX6ULL】时钟系统与定时器(EPIT & GPT)
c语言·arm开发·嵌入式硬件·学习·51单片机
mmmmath_33 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z3 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.3 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好3 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法