3160. Find the Number of Distinct Colors Among the Balls
JAVA
class Solution { public int[] queryResults(int limit, int[][] queries) { Map<Integer, Integer> g = new HashMap<>(); Map<Integer, Integer> cnt = new HashMap<>(); int m = queries.length; int[] ans = new int[m]; for (int i = 0; i < m; ++i) { int x = queries[i][0], y = queries[i][1]; cnt.merge(y, 1, Integer::sum); if (g.containsKey(x) && cnt.merge(g.get(x), -1, Integer::sum) == 0) { cnt.remove(g.get(x)); } g.put(x, y); ans[i] = cnt.size(); } return ans; } }
C++
class Solution { public: vector<int> queryResults(int limit, vector<vector<int>>& queries) { unordered_map<int, int> g; unordered_map<int, int> cnt; vector<int> ans; for (auto& q : queries) { int x = q[0], y = q[1]; cnt[y]++; if (g.contains(x) && --cnt[g[x]] == 0) { cnt.erase(g[x]); } g[x] = y; ans.push_back(cnt.size()); } return ans; } };
PYTHON
class Solution: def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]: g = {} cnt = Counter() ans = [] for x, y in queries: cnt[y] += 1 if x in g: cnt[g[x]] -= 1 if cnt[g[x]] == 0: cnt.pop(g[x]) g[x] = y ans.append(len(cnt)) return ans
Comments
Post a Comment