- Leetcode 3160. Find the Number of Distinct Colors Among the Balls
- 1. 解题思路
- 2. 代码实现
- 题目链接:3160. Find the Number of Distinct Colors Among the Balls
1. 解题思路
这一题思路上同样比较清晰,我们只需用两个hash table来分别记录每一个位置的颜色以及每一个颜色当前出现的次数,此时,我们即可对每一次操作快速地维护和更新当前的distinct颜色的个数了。
2. 代码实现
给出python代码实现如下:
class Solution:def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]:colors = {}cnt = defaultdict(int)distinct = 0ans = [0 for _ in queries]for i, (idx, c) in enumerate(queries):if idx not in colors:colors[idx] = ccnt[c] += 1if cnt[c] == 1:distinct += 1else:oc = colors[idx]colors[idx] = ccnt[oc] -= 1if cnt[oc] == 0:distinct -= 1cnt[c] += 1if cnt[c] == 1:distinct += 1ans[i] = distinctreturn ans
提交代码评测得到:耗时1148ms,占用内存68.4MB。