-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathheapLead.py
60 lines (43 loc) · 1.45 KB
/
heapLead.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Designing a leaderboard
"""
# Time complexity of O(nlogK)
class Leaderboard:
def __init__(self):
self.scores = {}
def addScore(self, playerId: int, score: int) -> None:
if playerId not in self.scores:
self.scores[playerId] = 0
self.scores[playerId] += score
def top(self, K: int) -> int:
print(self.scores)
heap = []
for val in self.scores.values():
heapq.heappush(heap, val)
# print(heap)
if len(heap) > K:
heapq.heappop(heap) #remove from the head of the heap -> the smallest value in the heap
# print(heap)
top = 0
for i in heap:
top += i
return top
def reset(self, playerId: int) -> None:
del self.scores[playerId]
# Time complexity of O(nlogn)
class Leaderboard:
def __init__(self):
self.scores = {}
def addScore(self, playerId: int, score: int) -> None:
if playerId not in self.scores:
self.scores[playerId] = 0
self.scores[playerId] += score
def top(self, K: int) -> int:
values = [value for key, value in sorted(self.scores.items(), key=lambda X: X[1])]
values.sort(reverse = True)
total = 0
for i in values[:K]:
total += i
return total
def reset(self, playerId: int) -> None:
del self.scores[playerId]