leetcode692

本文介绍了一种O(nlogk)时间复杂度和O(n)空间复杂度的解决方案,用于从给定的单词列表中找出出现频率最高的前k个单词。通过使用HashMap统计单词出现次数,然后使用自定义排序节点进行排序,最终返回按频率和字母顺序排列的前k个单词。
摘要由CSDN通过智能技术生成
题目大意:

给一非空的单词列表,返回前 k 个出现次数最多的单词。

返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。

O(n log k) 时间复杂度和 O(n) 空间复杂度解决。

来源:力扣(LeetCode
链接:https://leetcode-cn.com/problems/top-k-frequent-words/


解决思路:

首先使用HashMap记录每个单词的编号,然后统计每个单词的数目,最后按照题目意思排序即可。

时间复杂度:O(n log k) 空间复杂度:O(n)

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        struct node{
            string a;
            int num;
            node() {
                a = "", num = 0;
            }
            bool operator< (const node & x) const{
                if (num != x.num)
                    return num > x.num;
                return a < x.a;
            }
        };
        unordered_map<string, int> mp;
        node *p = new node[words.size()];
        int pnum = 0;
        vector<string> ans;
        for (auto s: words) {
            if (!mp.count(s)) {
                mp[s] = pnum++;
                p[mp[s]].a = s;
            } 
            p[mp[s]].num++;
        }
        sort(p, p + pnum);
        for (int i = 0; i < k; i++) {
            ans.push_back(p[i].a);
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值