|
| 1 | +/** |
| 2 | + * 3160. Find the Number of Distinct Colors Among the Balls |
| 3 | + * https://leetcode.com/problems/find-the-number-of-distinct-colors-among-the-balls/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer limit and a 2D array queries of size n x 2. |
| 7 | + * |
| 8 | + * There are limit + 1 balls with distinct labels in the range [0, limit]. Initially, |
| 9 | + * all balls are uncolored. For every query in queries that is of the form [x, y], |
| 10 | + * you mark ball x with the color y. After each query, you need to find the number |
| 11 | + * of distinct colors among the balls. |
| 12 | + * |
| 13 | + * Return an array result of length n, where result[i] denotes the number of distinct |
| 14 | + * colors after ith query. |
| 15 | + * |
| 16 | + * Note that when answering a query, lack of a color will not be considered as a color. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} limit |
| 21 | + * @param {number[][]} queries |
| 22 | + * @return {number[]} |
| 23 | + */ |
| 24 | +var queryResults = function(limit, queries) { |
| 25 | + const result = []; |
| 26 | + |
| 27 | + for (let i = 0, colors = new Map(), counts = new Map(); i < queries.length; i++) { |
| 28 | + const [index, color] = queries[i]; |
| 29 | + if (colors.has(index)) { |
| 30 | + const prev = colors.get(index); |
| 31 | + counts.set(prev, counts.get(prev) - 1); |
| 32 | + if (!counts.get(prev)) counts.delete(prev); |
| 33 | + } |
| 34 | + colors.set(index, color); |
| 35 | + counts.set(color, (counts.get(color) ?? 0) + 1); |
| 36 | + result.push(counts.size); |
| 37 | + } |
| 38 | + |
| 39 | + return result; |
| 40 | +}; |
0 commit comments