[LeetCode] Find the Number of Distinct Colors Among the Balls

3160. Find the Number of Distinct Colors Among the Balls

You are given an integer limit and a 2D array queries of size n x 2.

There are limit + 1 balls with distinct labels in the range [0, limit]. Initially, all balls are uncolored. For every query in queries that is of the form [x, y], you mark ball x with the color y. After each query, you need to find the number of distinct colors among the balls.

Return an array result of length n, where result[i] denotes the number of distinct colors after ith query.

Note that when answering a query, lack of a color will not be considered as a color.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> queryResults(int limit, vector<vector<int>>& Q) {
unordered_map<int,int> c,rc;
vector<int> res;
for(auto& q : Q) {
int b = q[0], col = q[1];
if(c.count(b)) {
if(--rc[c[b]] == 0) rc.erase(c[b]);
}
c[b] = col;
rc[col]++;
res.push_back(rc.size());
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/26/PS/LeetCode/find-the-number-of-distinct-colors-among-the-balls/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.