louzhedong / blog

前端基础,深入以及算法数据结构

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

前K个高频单词

louzhedong opened this issue · comments

题目

给一非空的单词列表,返回前 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);
};