LeetCode[347] 前 K 个高频元素

https://leetcode.cn/problems/top-k-frequent-elements/description/

主要是用hash表
数据个数给定了,但是数据范围没有给定,可能是负数。
所以需要map来记录每个数的id

class Solution {
public:
    map<int, int> id;
    unordered_map<int, int> nid;
    int st[100010];
    int n = 1;
    pair<int, int> cnt[100010];
    vector<int> topKFrequent(vector<int> &nums, int k)
    {
        vector<int> ans;
        for (auto x : nums)
        {
            if (!id[x])
            {
                id[x] = n;
                nid[n] = x;
                n++;
            }
            cnt[id[x]].first++;
            cnt[id[x]].second = id[x];
        }
        sort(cnt + 1, cnt + n + 1);
        for (int i = n, j = 1; j <= k; i--, j ++) {
            ans.push_back(nid[cnt[i].second]);
        }
        return ans;
    }
};
posted @   星星亮了欸  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示