1207.Unique Number of Occurrences === ###### tags: `Easy`,`Array`,`Hash Table` [1207. Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) ### 題目描述 Given an array of integers `arr`, return `true` if the number of occurrences of each value in the array is **unique**, or `false` otherwise. ### 範例 **Example 1:** ``` Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. ``` **Example 2:** ``` Input: arr = [1,2] Output: false ``` **Example 3:** ``` Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true ``` **Constraints**: * `1 <= arr.length <= 1000` * `-1000 <= arr[i] <= 1000` ### 解答 #### Java ```java= class Solution { public boolean uniqueOccurrences(int[] arr) { HashMap<Integer, Integer> hm = new HashMap<>(); for(Integer num : arr) { hm.put(num, hm.getOrDefault(num, 0) + 1); } return hm.size() == new HashSet<>(hm.values()).size(); } } ``` > [name=Kobe][time=Wed, Nov 30] #### Python ```python= class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: return len(Counter(arr)) == len(set(Counter(arr).values())) ``` > [name=Kobe][time=Wed, Nov 30] ```python= class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: mapping = {} for v in arr: if v not in mapping: mapping[v] = 0 mapping[v] += 1 value_set = set() for v in mapping: if mapping[v] in value_set: return False value_set.add(mapping[v]) return True ``` > 我是廢物寫好長,但是過ㄌ[name=GP] #### Javascript ```javascript= function uniqueOccurrences(arr) { const map = new Map(); for (const num of arr) { map.set(num, (map.get(num) || 0) + 1); } return map.size === new Set(map.values()).size; } ``` > 昨天學會用map跟set真的是太好用惹! > [name=Marsgoat] [time= Nov 30, 2022] #### TypeScript ```typescript= function uniqueOccurrences(arr: number[]): boolean { const map = new Map(); arr.forEach((key) => { map.set(key, (map.get(key) ?? 0) + 1); }); // map.size 跟 value 組成的 set.size 不一樣就代表有重複 return map.size === new Set(map.values()).size; } /* * Map.prototype.set(key, value): * 設置鍵名 key 對應的鍵值為 value,然後回傳整個 Map 結構。 * 如果 key 已經有值,則鍵值會被更新,否則就新生成該鍵。 * * Map.prototype.get(key): * 讀取 key 對應的鍵值,如果找不到 key,回傳 undefined。 */ ``` > the 抄 > [name=sheep] [time= Nov 30, 2022] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)