Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前K个高频单词 #255

Open
louzhedong opened this issue May 20, 2021 · 0 comments
Open

前K个高频单词 #255

louzhedong opened this issue May 20, 2021 · 0 comments

Comments

@louzhedong
Copy link
Owner

题目

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

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

示例 1:

输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。

示例 2:

输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。

思路

用一个map来保存各个单词出现的次数,然后取出它们的key值组成数组,对数组按元素个数进行排序,当元素个数相同时,返回排在前面的字母

解答

/**
 * @param {string[]} words
 * @param {number} k
 * @return {string[]}
 */
var topKFrequent = function(words, k) {
    const map = new Map();
    for (let i = 0, length = words.length; i < length; i++) {
        const current = words[i];
        if (map.get(current)) {
            map.set(current, map.get(current) + 1)
        } else {
            map.set(current, 1);
        }
    }

    const keyArray = [...map.keys()];
    console.log(keyArray);
    keyArray.sort((a, b) => {
        let numberOfA = map.get(a);
        let numberOfB = map.get(b);
        if (numberOfA === numberOfB) {
            return a > b ? 1 : -1;
        }
        return numberOfB - numberOfA;
    });
    return keyArray.slice(0, k);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant