[LeetCode] 3238. Find the Number of Winning Players

You are given an integer n representing the number of players in a game and a 2D array pick where pick[i] = [xi, yi] represents that the player x picked a ball of color y.

Player i wins the game if they pick strictly more than i balls of the same color. In other words,

Player 0 wins if they pick any ball.
Player 1 wins if they pick at least two balls of the same color.
...
Player i wins if they pick at least i + 1 balls of the same color.
Return the number of players who win the game.

Note that multiple players can win the game.

Example 1:
Input: n = 4, pick = [[0,0],[1,0],[1,0],[2,1],[2,1],[2,0]]
Output: 2

Explanation:
Player 0 and player 1 win the game, while players 2 and 3 do not win.

Example 2:
Input: n = 5, pick = [[1,1],[1,2],[1,3],[1,4]]
Output: 0

Explanation:
No player wins the game.

Example 3:
Input: n = 5, pick = [[1,1],[2,4],[2,4],[2,4]]
Output: 1

Explanation:
Player 2 wins the game by picking 3 balls with color 4.

Constraints:
2 <= n <= 10
1 <= pick.length <= 100
pick[i].length == 2
0 <= xi <= n - 1
0 <= yi <= 10

求出胜利玩家的数目。

给你一个整数 n ,表示在一个游戏中的玩家数目。同时给你一个二维整数数组 pick ,其中 pick[i] = [xi, yi] 表示玩家 xi 获得了一个颜色为 yi 的球。

如果玩家 i 获得的球中任何一种颜色球的数目 严格大于 i 个,那么我们说玩家 i 是胜利玩家。换句话说:

如果玩家 0 获得了任何的球,那么玩家 0 是胜利玩家。
如果玩家 1 获得了至少 2 个相同颜色的球,那么玩家 1 是胜利玩家。
...
如果玩家 i 获得了至少 i + 1 个相同颜色的球,那么玩家 i 是胜利玩家。
请你返回游戏中 胜利玩家 的数目。

注意,可能有多个玩家是胜利玩家。

思路

这道题的思路是统计/counting sort。因为玩家有 n 个,球的颜色至多有 10 种,所以这里我创建一个二维数组记录过程中每个玩家拿到的不同颜色的球的数量。这里我同时创建了一个 boolean 数组记录每个玩家是否胜利,如果某个玩家已经胜利了,他之后拿再多的球都不要再重复计算了。当然这里也可以扫描两次,第一次先把二维数组里球的数量统计完毕,再次扫描二维数组,看玩家是否满足胜利条件。

复杂度

时间O(n)
空间O(nm) - n个玩家,m种颜色的球

代码

Java实现

class Solution {
    public int winningPlayerCount(int n, int[][] pick) {
        int res = 0;
        boolean[] win = new boolean[n + 1];
        int[][] map = new int[n + 1][11];
        for (int[] p : pick) {
            int player = p[0];
            int color = p[1];
            map[player][color]++;
            if (map[player][color] > player && !win[player]) {
                res++;
                win[player] = true;
            }
        }
        return res;
    }
}
posted @ 2024-11-23 02:42  CNoodle  阅读(13)  评论(0编辑  收藏  举报