Skip to content

Commit 60af31f

Browse files
committed
Day 37: Return top K frequent integers in an array
1 parent ae1e032 commit 60af31f

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

day37/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
Question of the day: https://leetcode.com/problems/top-k-frequent-elements/#/description
2+
3+
Given a non-empty array of integers, return the k most frequent elements.
4+
5+
For example,
6+
Given `[1,1,1,2,2,3]` and `k = 2`, return `[1,2]`.
7+
8+
Note:
9+
* You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
10+
* Your algorithm's time complexity must be better than O(n log n), where
11+
n is the array's size.
12+
13+
## Ideas
14+
15+
Can't do a normal sort, since that alone will take `O(nlogn)` runtime.
16+
The input array isn't sorted, so we need to keep track of a count and organize
17+
that count somehow as we iterate through the integers in the array. There
18+
doesn't seem to be any constraints on the types of integers on the array,
19+
so I'll assume that possible elements in the array range from -maxInt to maxInt
20+
.
21+
22+
I think I can actually use radix sort again. Same idea as the challenge from
23+
[Day 36](../day36).
24+
25+
26+
## Code
27+
[Python](./topKFrequent.py)
28+
29+
## Follow-up
30+
31+
redo this using python `collections` library

day37/topKFrequent.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
def topKFrequent(nums, k):
2+
if len(nums) == 0:
3+
return []
4+
5+
freqs = dict()
6+
for num in nums:
7+
if num in freqs:
8+
freqs[num] += 1
9+
else:
10+
freqs[num] = 1
11+
12+
buckets = [None for i in xrange(max(freqs.keys())+1)]
13+
14+
for num in freqs:
15+
freq = freqs[num]
16+
if buckets[freq]:
17+
buckets[freq].append(num)
18+
else:
19+
buckets[freq] = [num]
20+
21+
ret = []
22+
i = len(buckets)-1
23+
addedCount = 0
24+
offset = 0
25+
while addedCount < k:
26+
while not buckets[i-offset-addedCount]:
27+
offset += 1
28+
ret += buckets[i-offset-addedCount]
29+
addedCount += 1
30+
31+
return ret
32+
33+
def testTopKFrequent():
34+
assert set(topKFrequent([], 0)) == set([])
35+
assert set(topKFrequent([1], 1)) == set([1])
36+
assert set(topKFrequent([1,1,1,2,2,3], 2)) == set([1, 2])
37+
assert set(topKFrequent([-1,-1,-1,2,2,3], 2)) == set([-1, 2])
38+
assert set(topKFrequent([1,1,1,2,2,3], 3)) == set([1, 2, 3])
39+
assert set(topKFrequent([1, 2, 3, 4, 5], 1)) == set([1, 2, 3, 4, 5])
40+
41+
def main():
42+
testTopKFrequent()
43+
44+
if __name__ == "__main__":
45+
main()

0 commit comments

Comments
 (0)