Open songyy5517 opened 6 months ago
Approach: HashMap & HashSet
Complexity Analysis
class Solution {
public boolean uniqueOccurrences(int[] arr) {
// Intuition: HashMap & HashSet.
// 1. Exception handling
if (arr == null || arr.length == 0)
return false;
// 2. Define HashMap
HashMap<Integer, Integer> hm = new HashMap();
// 3. Calculate the ocurrences
for (int i : arr)
hm.put(i, hm.getOrDefault(i, 0) + 1);
return hm.size() == new HashSet(hm.values()).size();
}
}
2024/5/16
getOrDefualt
to update the hashmap;hm.values()
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:
Example 2:
Example 3:
Intuition This problem can be broken down into two subtasks. First, we need to calculate the ocurrences of each element in the array. Then we have to determine whether there exist same ocurrences. For the first task, we can use hashmap to record the occurences of each element when looping though the array. For the second task, considering the non-repetitive property of Set, we can use a hashset to store all the occurence values. If the size of hashset is the same as the size of hashmap, then the occurences of each value is unique, return true; vice versa.