leetcode 692. 前K个高频单词

96 阅读1分钟

c++

class Solution {
public:
    struct Node {
        string x;
        int val;
        Node(string x, int val): x(x), val(val) {}
        bool operator()(const Node& b) const {
            if (val - b.val) val < b.val;
            return x < b.x;
        }
    };
    struct cmp{
        bool operator()(Node&a, Node& b) {
            if (a.val != b.val) return a.val > b.val;
            return a.x < b.x;
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> _map;
        priority_queue<Node, vector<Node>, cmp> _heap;
        for (string x : words) _map[x]++;
        for (auto iter : _map) {
            _heap.push(Node(iter.first, iter.second));
            if (_heap.size() > k) _heap.pop();
        }
        vector<string> ans;
        while (_heap.size()) {
            Node tmp = _heap.top();
            _heap.pop();
            ans.push_back(tmp.x);
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

js

var topKFrequent = function(words, k) {
    var map = {};
    words.forEach(v => map[v] = (map[v] || 0)  + 1);
    var keys = Object.keys(map).sort((a, b) => map[b] - map[a] || a.localeCompare(b));
    return keys.slice(0, k);
};