Skip to content

feat: add solutions to lc problem: No.0692 #3760

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

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 46 additions & 28 deletions solution/0600-0699/0692.Top K Frequent Words/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ tags:

### 方法一:哈希表 + 排序

我们可以用一个哈希表 $\textit{cnt}$ 记录每一个单词出现的次数,然后对哈希表中的键值对按照值进行排序,如果值相同,按照键进行排序。

最后取出前 $k$ 个键即可。

时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为单词的个数。

<!-- tabs:start -->

#### Python3
Expand All @@ -86,23 +92,19 @@ class Solution:
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> cnt = new HashMap<>();
for (String v : words) {
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
for (String w : words) {
cnt.merge(w, 1, Integer::sum);
}
PriorityQueue<String> q = new PriorityQueue<>((a, b) -> {
int d = cnt.get(a) - cnt.get(b);
return d == 0 ? b.compareTo(a) : d;
Arrays.sort(words, (a, b) -> {
int c1 = cnt.get(a), c2 = cnt.get(b);
return c1 == c2 ? a.compareTo(b) : c2 - c1;
});
for (String v : cnt.keySet()) {
q.offer(v);
if (q.size() > k) {
q.poll();
List<String> ans = new ArrayList<>();
for (int i = 0; i < words.length && ans.size() < k; ++i) {
if (i == 0 || !words[i].equals(words[i - 1])) {
ans.add(words[i]);
}
}
LinkedList<String> ans = new LinkedList<>();
while (!q.isEmpty()) {
ans.addFirst(q.poll());
}
return ans;
}
}
Expand All @@ -115,13 +117,17 @@ class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto& v : words) ++cnt[v];
for (const auto& w : words) {
++cnt[w];
}
vector<string> ans;
for (auto& [key, _] : cnt) ans.emplace_back(key);
sort(ans.begin(), ans.end(), [&](const string& a, const string& b) -> bool {
return cnt[a] == cnt[b] ? a < b : cnt[a] > cnt[b];
for (const auto& [w, _] : cnt) {
ans.push_back(w);
}
ranges::sort(ans, [&](const string& a, const string& b) {
return cnt[a] > cnt[b] || (cnt[a] == cnt[b] && a < b);
});
ans.erase(ans.begin() + k, ans.end());
ans.resize(k);
return ans;
}
};
Expand All @@ -130,23 +136,35 @@ public:
#### Go

```go
func topKFrequent(words []string, k int) []string {
func topKFrequent(words []string, k int) (ans []string) {
cnt := map[string]int{}
for _, v := range words {
cnt[v]++
for _, w := range words {
cnt[w]++
}
ans := []string{}
for v := range cnt {
ans = append(ans, v)
for w := range cnt {
ans = append(ans, w)
}
sort.Slice(ans, func(i, j int) bool {
a, b := ans[i], ans[j]
return cnt[a] > cnt[b] || cnt[a] == cnt[b] && a < b
})
sort.Slice(ans, func(i, j int) bool { a, b := ans[i], ans[j]; return cnt[a] > cnt[b] || cnt[a] == cnt[b] && a < b })
return ans[:k]
}
```

#### TypeScript

```ts
function topKFrequent(words: string[], k: number): string[] {
const cnt: Map<string, number> = new Map();
for (const w of words) {
cnt.set(w, (cnt.get(w) || 0) + 1);
}
const ans: string[] = Array.from(cnt.keys());
ans.sort((a, b) => {
return cnt.get(a) === cnt.get(b) ? a.localeCompare(b) : cnt.get(b)! - cnt.get(a)!;
});
return ans.slice(0, k);
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
76 changes: 47 additions & 29 deletions solution/0600-0699/0692.Top K Frequent Words/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,13 @@ Note that &quot;i&quot; comes before &quot;love&quot; due to a lower alphabetica

<!-- solution:start -->

### Solution 1
### Solution 1: Hash Table + Sorting

We can use a hash table $\textit{cnt}$ to record the frequency of each word. Then, we sort the key-value pairs in the hash table by value, and if the values are the same, we sort by key.

Finally, we take the first $k$ keys.

The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of words.

<!-- tabs:start -->

Expand All @@ -82,23 +88,19 @@ class Solution:
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> cnt = new HashMap<>();
for (String v : words) {
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
for (String w : words) {
cnt.merge(w, 1, Integer::sum);
}
PriorityQueue<String> q = new PriorityQueue<>((a, b) -> {
int d = cnt.get(a) - cnt.get(b);
return d == 0 ? b.compareTo(a) : d;
Arrays.sort(words, (a, b) -> {
int c1 = cnt.get(a), c2 = cnt.get(b);
return c1 == c2 ? a.compareTo(b) : c2 - c1;
});
for (String v : cnt.keySet()) {
q.offer(v);
if (q.size() > k) {
q.poll();
List<String> ans = new ArrayList<>();
for (int i = 0; i < words.length && ans.size() < k; ++i) {
if (i == 0 || !words[i].equals(words[i - 1])) {
ans.add(words[i]);
}
}
LinkedList<String> ans = new LinkedList<>();
while (!q.isEmpty()) {
ans.addFirst(q.poll());
}
return ans;
}
}
Expand All @@ -111,13 +113,17 @@ class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto& v : words) ++cnt[v];
for (const auto& w : words) {
++cnt[w];
}
vector<string> ans;
for (auto& [key, _] : cnt) ans.emplace_back(key);
sort(ans.begin(), ans.end(), [&](const string& a, const string& b) -> bool {
return cnt[a] == cnt[b] ? a < b : cnt[a] > cnt[b];
for (const auto& [w, _] : cnt) {
ans.push_back(w);
}
ranges::sort(ans, [&](const string& a, const string& b) {
return cnt[a] > cnt[b] || (cnt[a] == cnt[b] && a < b);
});
ans.erase(ans.begin() + k, ans.end());
ans.resize(k);
return ans;
}
};
Expand All @@ -126,23 +132,35 @@ public:
#### Go

```go
func topKFrequent(words []string, k int) []string {
func topKFrequent(words []string, k int) (ans []string) {
cnt := map[string]int{}
for _, v := range words {
cnt[v]++
for _, w := range words {
cnt[w]++
}
ans := []string{}
for v := range cnt {
ans = append(ans, v)
for w := range cnt {
ans = append(ans, w)
}
sort.Slice(ans, func(i, j int) bool {
a, b := ans[i], ans[j]
return cnt[a] > cnt[b] || cnt[a] == cnt[b] && a < b
})
sort.Slice(ans, func(i, j int) bool { a, b := ans[i], ans[j]; return cnt[a] > cnt[b] || cnt[a] == cnt[b] && a < b })
return ans[:k]
}
```

#### TypeScript

```ts
function topKFrequent(words: string[], k: number): string[] {
const cnt: Map<string, number> = new Map();
for (const w of words) {
cnt.set(w, (cnt.get(w) || 0) + 1);
}
const ans: string[] = Array.from(cnt.keys());
ans.sort((a, b) => {
return cnt.get(a) === cnt.get(b) ? a.localeCompare(b) : cnt.get(b)! - cnt.get(a)!;
});
return ans.slice(0, k);
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
16 changes: 10 additions & 6 deletions solution/0600-0699/0692.Top K Frequent Words/Solution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto& v : words) ++cnt[v];
for (const auto& w : words) {
++cnt[w];
}
vector<string> ans;
for (auto& [key, _] : cnt) ans.emplace_back(key);
sort(ans.begin(), ans.end(), [&](const string& a, const string& b) -> bool {
return cnt[a] == cnt[b] ? a < b : cnt[a] > cnt[b];
for (const auto& [w, _] : cnt) {
ans.push_back(w);
}
ranges::sort(ans, [&](const string& a, const string& b) {
return cnt[a] > cnt[b] || (cnt[a] == cnt[b] && a < b);
});
ans.erase(ans.begin() + k, ans.end());
ans.resize(k);
return ans;
}
};
};
18 changes: 7 additions & 11 deletions solution/0600-0699/0692.Top K Frequent Words/Solution.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
func topKFrequent(words []string, k int) []string {
func topKFrequent(words []string, k int) (ans []string) {
cnt := map[string]int{}
for _, v := range words {
cnt[v]++
for _, w := range words {
cnt[w]++
}
ans := []string{}
for v := range cnt {
ans = append(ans, v)
for w := range cnt {
ans = append(ans, w)
}
sort.Slice(ans, func(i, j int) bool {
a, b := ans[i], ans[j]
return cnt[a] > cnt[b] || cnt[a] == cnt[b] && a < b
})
sort.Slice(ans, func(i, j int) bool { a, b := ans[i], ans[j]; return cnt[a] > cnt[b] || cnt[a] == cnt[b] && a < b })
return ans[:k]
}
}
24 changes: 10 additions & 14 deletions solution/0600-0699/0692.Top K Frequent Words/Solution.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> cnt = new HashMap<>();
for (String v : words) {
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
for (String w : words) {
cnt.merge(w, 1, Integer::sum);
}
PriorityQueue<String> q = new PriorityQueue<>((a, b) -> {
int d = cnt.get(a) - cnt.get(b);
return d == 0 ? b.compareTo(a) : d;
Arrays.sort(words, (a, b) -> {
int c1 = cnt.get(a), c2 = cnt.get(b);
return c1 == c2 ? a.compareTo(b) : c2 - c1;
});
for (String v : cnt.keySet()) {
q.offer(v);
if (q.size() > k) {
q.poll();
List<String> ans = new ArrayList<>();
for (int i = 0; i < words.length && ans.size() < k; ++i) {
if (i == 0 || !words[i].equals(words[i - 1])) {
ans.add(words[i]);
}
}
LinkedList<String> ans = new LinkedList<>();
while (!q.isEmpty()) {
ans.addFirst(q.poll());
}
return ans;
}
}
}
11 changes: 11 additions & 0 deletions solution/0600-0699/0692.Top K Frequent Words/Solution.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
function topKFrequent(words: string[], k: number): string[] {
const cnt: Map<string, number> = new Map();
for (const w of words) {
cnt.set(w, (cnt.get(w) || 0) + 1);
}
const ans: string[] = Array.from(cnt.keys());
ans.sort((a, b) => {
return cnt.get(a) === cnt.get(b) ? a.localeCompare(b) : cnt.get(b)! - cnt.get(a)!;
});
return ans.slice(0, k);
}
Loading