Skip to content

Commit df81712

Browse files
authored
Update top-k-frequent-elements.py
1 parent b768f5e commit df81712

1 file changed

Lines changed: 30 additions & 4 deletions

File tree

Python/top-k-frequent-elements.py

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Time: O(n) ~ O(n^2), O(n) on average.
1+
# Time: O(n)
22
# Space: O(n)
33

44
# Given a non-empty array of integers,
@@ -13,9 +13,35 @@
1313
# Your algorithm's time complexity must be better
1414
# than O(n log n), where n is the array's size.
1515

16-
from random import randint
17-
16+
# Bucket Sort Solution
1817
class Solution(object):
18+
def topKFrequent(self, nums, k):
19+
"""
20+
:type nums: List[int]
21+
:type k: int
22+
:rtype: List[int]
23+
"""
24+
counts = collections.defaultdict(int)
25+
for i in nums:
26+
counts[i] += 1
27+
buckets = [[] for _ in xrange(len(nums)+1)]
28+
for i, count in counts.iteritems():
29+
buckets[count].append(i)
30+
31+
result = []
32+
for i in reversed(xrange(len(buckets))):
33+
for j in xrange(len(buckets[i])):
34+
result.append(buckets[i][j])
35+
if len(result) == k:
36+
return result
37+
return result
38+
39+
40+
# Time: O(n) ~ O(n^2), O(n) on average.
41+
# Space: O(n)
42+
# Quick Select Solution
43+
from random import randint
44+
class Solution2(object):
1945
def topKFrequent(self, nums, k):
2046
"""
2147
:type nums: List[int]
@@ -64,7 +90,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums):
6490

6591
# Time: O(nlogk)
6692
# Space: O(n)
67-
class Solution2(object):
93+
class Solution3(object):
6894
def topKFrequent(self, nums, k):
6995
"""
7096
:type nums: List[int]

0 commit comments

Comments
 (0)