Skip to content

Commit d012062

Browse files
authored
Create design-a-leaderboard.py
1 parent eaed595 commit d012062

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Python/design-a-leaderboard.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Time: ctor: O(1)
2+
# add: O(1)
3+
# top: O(n)
4+
# reset: O(1)
5+
# Space: O(n)
6+
7+
import collections
8+
import random
9+
10+
11+
class Leaderboard(object):
12+
13+
def __init__(self):
14+
self.__lookup = collections.Counter()
15+
16+
def addScore(self, playerId, score):
17+
"""
18+
:type playerId: int
19+
:type score: int
20+
:rtype: None
21+
"""
22+
self.__lookup[playerId] += score
23+
24+
def top(self, K):
25+
"""
26+
:type K: int
27+
:rtype: int
28+
"""
29+
def kthElement(nums, k, compare):
30+
def PartitionAroundPivot(left, right, pivot_idx, nums, compare):
31+
new_pivot_idx = left
32+
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
33+
for i in xrange(left, right):
34+
if compare(nums[i], nums[right]):
35+
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
36+
new_pivot_idx += 1
37+
38+
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
39+
return new_pivot_idx
40+
41+
left, right = 0, len(nums) - 1
42+
while left <= right:
43+
pivot_idx = random.randint(left, right)
44+
new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)
45+
if new_pivot_idx == k:
46+
return
47+
elif new_pivot_idx > k:
48+
right = new_pivot_idx - 1
49+
else: # new_pivot_idx < k.
50+
left = new_pivot_idx + 1
51+
52+
scores = self.__lookup.values()
53+
kthElement(scores, K, lambda a, b: a > b)
54+
return sum(scores[:K])
55+
56+
def reset(self, playerId):
57+
"""
58+
:type playerId: int
59+
:rtype: None
60+
"""
61+
self.__lookup[playerId] = 0

0 commit comments

Comments
 (0)