力扣题目:独一无二的出现次数
题目链接: 1207.独一无二的出现次数
题目描述
代码思路
根据题目要求,可以使用哈希表来统计每个数字出现的次数,然后利用set集合的特性(不能添加重复的元素)来判断是否出现重复次数
代码纯享版
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int a : arr) {
map.put(a, map.getOrDefault(a, 0) + 1);
}
Set<Integer> set = new HashSet<Integer>();
for (Map.Entry<Integer, Integer> a : map.entrySet()) {
set.add(a.getValue());
}
return set.size() == map.size();
}
}
代码逐行解析版
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //使用map哈希表来保存每个数字及其出现的次数
for (int a : arr) { //遍历数组元素
map.put(a, map.getOrDefault(a, 0) + 1); //统计数字出现次数
}
Set<Integer> set = new HashSet<Integer>(); //set集合,用来添加没出现过的次数
for (Map.Entry<Integer, Integer> a : map.entrySet()) { //遍历整个map哈希表
set.add(a.getValue()); //set集合只会添加没出现过的次数
}
return set.size() == map.size(); //比较set集合的长度和map哈希表的长度
}
}