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;
}
}