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 xi
picked a ball of color yi.
Player iwins 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 leasti + 1 balls of the same color.
For each player, count how many balls of each color they picked. If any color count is greater than the player’s index, the player wins. This is a direct application of the problem’s definition.
classSolution {
public:int numberOfWinners(int n, vector<vector<int>>& pick) {
vector<unordered_map<int, int>> cnt(n);
for (auto& p : pick) cnt[p[0]][p[1]]++;
int ans =0;
for (int i =0; i < n; ++i) {
for (auto& [color, c] : cnt[i]) {
if (c > i) {
ans++;
break;
}
}
}
return ans;
}
};
classSolution {
publicintnumberOfWinners(int n, int[][] pick) {
Map<Integer, Integer>[] cnt =new HashMap[n];
for (int i = 0; i < n; ++i) cnt[i]=new HashMap<>();
for (int[] p : pick) cnt[p[0]].put(p[1], cnt[p[0]].getOrDefault(p[1], 0) + 1);
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int c : cnt[i].values()) {
if (c > i) {
ans++;
break;
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funnumberOfWinners(n: Int, pick: Array<IntArray>): Int {
val cnt = Array(n) { mutableMapOf<Int, Int>() }
for (p in pick) cnt[p[0]][p[1]] = cnt[p[0]].getOrDefault(p[1], 0) + 1var ans = 0for (i in0 until n) {
if (cnt[i].values.any { it > i }) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defnumberOfWinners(self, n: int, pick: list[list[int]]) -> int:
cnt = [{} for _ in range(n)]
for x, y in pick:
cnt[x][y] = cnt[x].get(y, 0) +1 ans =0for i in range(n):
if any(c > i for c in cnt[i].values()):
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnnumber_of_winners(n: i32, pick: Vec<Vec<i32>>) -> i32 {
let n = n asusize;
letmut cnt =vec![std::collections::HashMap::new(); n];
for p in pick {
*cnt[p[0] asusize].entry(p[1]).or_insert(0) +=1;
}
letmut ans =0;
for (i, m) in cnt.iter().enumerate() {
if m.values().any(|&c| c > i) {
ans +=1;
}
}
ans
}
}