Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
/**
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/
// O(n log n)
var topKFrequent = function(words, k) {
const map = {};
for(let word of words) {
map[word] = map[word] + 1 || 1;
}
let res = Object.keys(map).sort((a, b) => {
let diff = map[b] - map[a];
if(diff === 0) {
/*
sorting descend in an alphabetic order. i.e. a -> b -> c -> d
localeCompare() returns one of 3 numbers indicating the sort order.
-1 if sorted before
1 if sorted after
0 if equal
*/
return a.localeCompare(b);
}
else {
return diff;
}
})
return res.slice(0, k);
};