-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtop-K-Frequent-Words.py
More file actions
44 lines (32 loc) · 1.2 KB
/
top-K-Frequent-Words.py
File metadata and controls
44 lines (32 loc) · 1.2 KB
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
40
41
42
43
44
# nlogn time
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
d = {}
for word in words:
if word not in d:
d[word]=1
else:
d[word]+=1
# sort the dictionary d by the dictionary value
# using lambda for the key value, so that it sorts
# by each dictionary value in reverse (greatest value to least)
# for each word in dictionary
# first, sorts by values in dictionary
# then sorts again by word, which alphabetizes
ret = sorted(d, key=lambda word: (-d[word], word))
return ret[:k]
# another nlogn solution
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
ret=[]
freq = {}
for word in words:
if word not in freq:
freq[word]=1
else:
freq[word]+=1
sorted_freq = {key: value for key, value in sorted(freq.items(), key=lambda x: [-x[1], x[0]])}
for word in sorted_freq:
ret.append(word)
if len(ret)==k:
return ret