LeetCode problem#1207
Unique Number of Occurrences
Solved in 1 languageJava
Solution
25 lines
1class Solution {
2 public boolean uniqueOccurrences(int[] arr) {
3 HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
4 HashSet<Integer> hashSet = new HashSet<Integer>();
5
6 for (int i = 0; i < arr.length; i++) {
7 if (hashMap.containsKey(arr[i])) {
8 hashMap.put(arr[i], hashMap.get(arr[i]) + 1);
9 }
10 else {
11 hashMap.put(arr[i], 1);
12 }
13 }
14
15 // Note: you can also use hashMap.values() instead of having to go through the key
16 for (int n : hashMap.keySet()) {
17 if (hashSet.contains(hashMap.get(n))) {
18 return false;
19 }
20 hashSet.add(hashMap.get(n));
21 }
22
23 return true;
24 }
25}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.