FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_02/id_129/LeetCode_692_129.java at master · feixiangcode/algorithm · GitHub
feixiangcode
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_02
/
id_129
/
LeetCode_692_129.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
39 lines (33 loc) · 1.46 KB
Breadcrumbs
algorithm
/
Week_02
/
id_129
/
LeetCode_692_129.java
Copy path
File metadata and controls
39 lines (33 loc) · 1.46 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import
java
.
util
.*;
public
class
LeetCode_692_129
{
public
List
<
String
>
topKFrequent
(
String
[]
words
,
int
k
) {
List
<
String
>
result
=
new
LinkedList
<>();
Map
<
String
,
Integer
>
map
=
new
HashMap
<>();
for
(
int
i
=
0
;
i
<
words
.
length
;
i
++) {
map
.
put
(
words
[
i
],
map
.
getOrDefault
(
words
[
i
],
0
) +
1
);
}
PriorityQueue
<
Map
.
Entry
<
String
,
Integer
>>
pq
=
new
PriorityQueue
<>(
(
a
,
b
) ->
a
.
getValue
() ==
b
.
getValue
() ?
b
.
getKey
().
compareTo
(
a
.
getKey
()) :
a
.
getValue
() -
b
.
getValue
()
);
for
(
Map
.
Entry
<
String
,
Integer
>
entry
:
map
.
entrySet
()) {
pq
.
offer
(
entry
);
if
(
pq
.
size
() >
k
)
pq
.
poll
();
}
while
(!
pq
.
isEmpty
())
result
.
add
(
0
,
pq
.
poll
().
getKey
());
return
result
;
}
public
List
<
String
>
topKFrequent2
(
String
[]
words
,
int
k
) {
List
<
String
>
list
=
new
ArrayList
<>();
Map
<
String
,
Integer
>
map
=
new
HashMap
<>();
for
(
String
word
:
words
)
map
.
put
(
word
,
map
.
getOrDefault
(
word
,
0
) +
1
);
Set
<
Map
.
Entry
<
String
,
Integer
>>
set
=
new
TreeSet
<>(
(
a
,
b
) ->
a
.
getValue
() ==
b
.
getValue
() ?
a
.
getKey
().
compareTo
(
b
.
getKey
()) :
b
.
getValue
() -
a
.
getValue
()
);
for
(
Map
.
Entry
<
String
,
Integer
>
entry
:
map
.
entrySet
())
set
.
add
(
entry
);
Iterator
<
Map
.
Entry
<
String
,
Integer
>>
iter
=
set
.
iterator
();
while
(
k
-- >
0
)
list
.
add
(
iter
.
next
().
getKey
());
return
list
;
}
}
Back
|
FazBrowse Home
|
New Git URL