题目描述
给一非空的单词列表,返回前 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 次。
ES6之Map数据结构
ES6的Map数据结构,类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。
const m = new Map();
const o = {p: 'Hello World'};
m.set(o, 'content');
m.get(o);
m.has(o) // true
m.delete(o) // true
m.has(o) // false
上面代码使用Map结构的set方法,将对象o当作m的一个键,然后又使用get方法读取这个键,接着使用delete方法删除了这个键。
Array.from()
Array.from()方法对一个类似数组或可迭代对象创建一个新的,浅拷贝数组实例。
语法:
Array.from(arrayLike[, mapFn[, thisArg]])
- arrayLike -- 想要转换成数组的伪数组对象或可迭代对象。
- mapFn --
可选--如果指定了该参数,新数组中的每个元素会执行该回调函数 - thisArg --
可选--可选参数,执行回调函数mapFn时this对象。 - 返回值 -- 一个新的
数组实例。
字符串比较之localeCompare
- stringObject.localeCompare(target)
- 描述:要以本地特定的顺序与stringObject进行比较的字符串
- 返回值:返回数字。如果stringObject小于target,则localeCompare()返回小于0的数。stringObject大于target,则该方法返回大于0的数。如果两个字符串相等,或者根据本地排序没有区别,该方法返回0.
- 使用的本地规则有汉字和英语的。
- a.localCompare(b) -- 升序
- b.localCompare(a) -- 降序
代码
var topKFrequent = function(words, k){
let map = new Map();
for(let word of words){
// map.get可以得到当前key的value,没有就赋值0,有就拿出value然后加1
map.set(word, (map.get(word) || 0) + 1);
}
let arr = Array.from(map);
arr.sort((a, b) ==> a[1] === b[1] ? a[0].localecompare(b[0]) : a - b;
// 选择数组的一部分,并返回新数组
let top = arr.slice(0, k);
// 使用为每个数组元素调用函数的结果创建新数组
return top.map(a => a[0]);
}