###### tags: `Leetcode` `easy` `hash` `python` `c++` # 1207. Unique Number of Occurrences ## [題目連結:] https://leetcode.com/problems/unique-number-of-occurrences/description/ ## 題目: 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 ``` ## 解題想法: * 此題為,判斷數組中的每個數,出現次數是否皆不同 * 兩個字典判斷: * 第一個字典 * key: 數字 * val: 出現次數 * 第二個字典 * key: 出現次數 * val: Bool ## Python: ``` python= from collections import defaultdict class Solution(object): def uniqueOccurrences(self, arr): """ :type arr: List[int] :rtype: bool """ dic=defaultdict(int) num=defaultdict(bool) for val in arr: dic[val]+=1 for key in dic: if dic[key] in num: return False num[dic[key]]=True return True ``` ## C++: ``` cpp= class Solution { public: bool uniqueOccurrences(vector<int>& arr) { unordered_map<int,int> dic; unordered_map<int,bool> appear; for (int val: arr){ dic[val]+=1; } //unordered_map //first: key //second: value for (const auto & item: dic){ if (appear.find(item.second)!=appear.end()) return false; appear[item.second]=true; } return true; } }; ```