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

  1. class Solution:
  2. def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]:
  3. n=len(queries)
  4. ans=[0]*n
  5. mp={}
  6. color=defaultdict(int)
  7. i=0
  8. for x, c in queries:
  9. if x in mp:
  10. c0=mp[x]
  11. color[c0]-=1
  12. if color[c0]==0:
  13. color.pop(c0)
  14. mp[x]=c
  15. color[c]+=1
  16. ans[i]=len(color)
  17. i+=1
  18. return ans

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章