Skip to content

Commit 8e79dd9

Browse files
committed
feat: add 0237 Top K Frequent Elements solution
1 parent 10ba4e0 commit 8e79dd9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3+
plus = [0] * (10**4 + 1)
4+
minus = [0] * (10**4 + 1)
5+
6+
for i in range(len(nums)):
7+
if nums[i] < 0:
8+
minus[-(nums[i])] += 1
9+
else:
10+
plus[nums[i]] += 1
11+
12+
ans = []
13+
for i in range(k):
14+
if max(max(minus), max(plus)) == max(plus):
15+
idx = plus.index(max(plus))
16+
ans.append(idx)
17+
plus[idx] = 0
18+
else:
19+
idx = minus.index(max(minus))
20+
ans.append(-(idx))
21+
minus[idx] = 0
22+
23+
return ans
24+

0 commit comments

Comments
 (0)