Skip to content

Commit f7ccc12

Browse files
committed
Add solution #692
1 parent 5d66fb1 commit f7ccc12

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,7 @@
522522
688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium|
523523
689|[Maximum Sum of 3 Non-Overlapping Subarrays](./0689-maximum-sum-of-3-non-overlapping-subarrays.js)|Hard|
524524
690|[Employee Importance](./0690-employee-importance.js)|Medium|
525+
692|[Top K Frequent Words](./0692-top-k-frequent-words.js)|Medium|
525526
693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy|
526527
695|[Max Area of Island](./0695-max-area-of-island.js)|Medium|
527528
696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy|
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* 692. Top K Frequent Words
3+
* https://leetcode.com/problems/top-k-frequent-words/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of strings words and an integer k, return the k most frequent strings.
7+
*
8+
* Return the answer sorted by the frequency from highest to lowest. Sort the words with
9+
* the same frequency by their lexicographical order.
10+
*/
11+
12+
/**
13+
* @param {string[]} words
14+
* @param {number} k
15+
* @return {string[]}
16+
*/
17+
var topKFrequent = function(words, k) {
18+
const map = new Map();
19+
words.forEach(word => map.set(word, (map.get(word) || 0) + 1));
20+
return [...map.entries()]
21+
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
22+
.slice(0, k)
23+
.map(([word]) => word);
24+
};

0 commit comments

Comments
 (0)