1244. Design A Leaderboard
Разработайте класс Leaderboard, который содержит 3 функции: addScore(playerId, score): Обновляет таблицу лидеров, добавляя счет к счету данного игрока. Если в таблице лидеров нет игрока с таким id, добавьте его в таблицу лидеров с заданным счетом. top(K): returns сумму очков K лучших игроков. reset(playerId): Сбрасывает счет игрока с заданным идентификатором в 0 (другими словами, стирает его из таблицы лидеров). Гарантируется, что игрок был добавлен в таблицу лидеров до вызова этой функции. Изначально таблица лидеров пуста.
例:
Input:
["Leaderboard","addScore","addScore","addScore","addScore","addScore","top","reset","reset","addScore","top"]
[[],[1,73],[2,56],[3,39],[4,51],[5,4],[1],[1],[2],[2,51],[3]]
Output:
[null,null,null,null,null,null,73,null,null,null,141]
C# 解法
照合済み/オリジナルusing System;
using System.Collections.Generic;
using System.Linq;
public class Leaderboard {
private Dictionary<int, int> scores;
public Leaderboard() {
scores = new Dictionary<int, int>();
}
public void AddScore(int playerId, int score) {
if (scores.ContainsKey(playerId)) {
scores[playerId] += score;
} else {
scores[playerId] = score;
}
}
public int Top(int K) {
return scores.Values.OrderByDescending(x => x).Take(K).Sum();
}
public void Reset(int playerId) {
if (scores.ContainsKey(playerId)) {
scores[playerId] = 0;
}
}
}
C++ 解法
自動ドラフト、提出前に確認#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class Leaderboard {
private unordered_map<int, int> scores;
public Leaderboard() {
scores = new unordered_map<int, int>();
}
public void AddScore(int playerId, int score) {
if (scores.count(playerId)) {
scores[playerId] += score;
} else {
scores[playerId] = score;
}
}
public int Top(int K) {
return scores.Values.OrderByDescending(x => x).Take(K).Sum();
}
public void Reset(int playerId) {
if (scores.count(playerId)) {
scores[playerId] = 0;
}
}
}
Java 解法
照合済み/オリジナルimport java.util.*;
public class Leaderboard {
private Map<Integer, Integer> scores;
public Leaderboard() {
scores = new HashMap<>();
}
public void addScore(int playerId, int score) {
scores.put(playerId, scores.getOrDefault(playerId, 0) + score);
}
public int top(int K) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.addAll(scores.values());
int sum = 0;
for (int i = 0; i < K && !maxHeap.isEmpty(); i++) {
sum += maxHeap.poll();
}
return sum;
}
public void reset(int playerId) {
scores.put(playerId, 0);
}
}
Python 解法
照合済み/オリジナルfrom collections import defaultdict
class Leaderboard:
def __init__(self):
self.scores = defaultdict(int)
def addScore(self, playerId, score):
self.scores[playerId] += score
def top(self, K):
return sum(sorted(self.scores.values(), reverse=True)[:K])
def reset(self, playerId):
self.scores[playerId] = 0
Go 解法
照合済み/オリジナルimport (
"sort"
"sync"
)
type Leaderboard struct {
scores map[int]int
mu sync.Mutex
}
func Constructor() Leaderboard {
return Leaderboard{scores: make(map[int]int)}
}
func (lb *Leaderboard) AddScore(playerId int, score int) {
lb.mu.Lock()
defer lb.mu.Unlock()
lb.scores[playerId] += score
}
func (lb *Leaderboard) Top(K int) int {
lb.mu.Lock()
defer lb.mu.Unlock()
allScores := make([]int, 0, len(lb.scores))
for _, score := range lb.scores {
allScores = append(allScores, score)
}
sort.Sort(sort.Reverse(sort.IntSlice(allScores)))
sum := 0
for i := 0; i < K && i < len(allScores); i++ {
sum += allScores[i]
}
return sum
}
func (lb *Leaderboard) Reset(playerId int) {
lb.mu.Lock()
defer lb.mu.Unlock()
lb.scores[playerId] = 0
}
Algorithm
addScore(playerId, score):
Если игрок уже существует в таблице лидеров, добавляем к его текущему счету новое значение.
Если игрок не существует, добавляем его с заданным счетом.
top(K):
Сортируем игроков по их счету в порядке убывания.
Возвращаем сумму очков K лучших игроков.
reset(playerId):
Устанавливаем счет игрока в 0.
😎
Vacancies for this task
有効な求人 with overlapping task tags are 表示.