1244. Design A Leaderboard

LeetCode medium original: C# #csharp #design #hash-table #leetcode #matrix #medium #sort
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

Разработайте класс 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 표시됨.

전체 채용
아직 활성 채용이 없습니다.