Leetcode 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 = 0
        ans = [0 for _ in queries]
        for i, (idx, c) in enumerate(queries):
            if idx not in colors:
                colors[idx] = c
                cnt[c] += 1
                if cnt[c] == 1:
                    distinct += 1
            else:
                oc = colors[idx]
                colors[idx] = c
                cnt[oc] -= 1
                if cnt[oc] == 0:
                    distinct -= 1
                cnt[c] += 1
                if cnt[c] == 1:
                    distinct += 1
            ans[i] = distinct
        return ans

提交代码评测得到:耗时1148ms,占用内存68.4MB。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值