herrDeng網內搜尋

自訂搜尋

Ads

2025年2月7日 星期五

Python C++ hashmap解Leetcode 3160 Find the Number of Distinct Colors Am...


Python C++  hashmap解Leetcode 3160  Find the Number of Distinct Colors Among the Balls
嘗試2個hashmap來解決。由於實際運行,可以說,Python dict 比 C++ unordered_map 快得多
[Py3 code請進]

----
Try 2 hash maps to solve. Due to real runs, It can be said, Python dict is much faster than C++ unordered_map

class Solution:
    def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]:
        n=len(queries)
        ans=[0]*n
        mp={}
        color=defaultdict(int)
        i=0
        for x, c in queries:
            if x in mp:
                c0=mp[x]
                color[c0]-=1
                if color[c0]==0:
                    color.pop(c0)
            mp[x]=c
            color[c]+=1
            ans[i]=len(color)
            i+=1
        return ans
        

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章