*1244. Design A Leaderboard

https://leetcode.com/problems/design-a-leaderboard/description/

solution

from heapq import heappop, heappush, heapify

class Leaderboard:
    def __init__(self):
        self.d = {}
        self.q = []

    def add_score(self, pid: int, score: int):
        if pid not in self.d:
            self.d[pid] = 0
        self.d[pid] -= score
        heappush(self.q, [self.d[pid], pid])

    def top(self, k: int) -> int:
        tem_d, tem_q, ans = {}, [], 0
        for _ in range(k):
            while(self.q and (self.q[0][1] not in self.d or self.d[self.q[0][1]] != self.q[0][0])):
                heappop(self.q)
            if self.q:
                s, i = heappop(self.q)
                self.d.pop(i)
                ans -= s
                tem_q.append([s, i])
                tem_d[i] = s
        self.q += tem_q
        self.d |= tem_d
        heapify(self.q)
        return ans

    def reset(self, pid: int):
        self.d[pid] = 0
        heappush(self.q, [self.d[pid], pid])

时间复杂度:O() 空间复杂度:O()

Last updated