独一无二的出现次数(简单)
2020年10月28日
题目来源:力扣
解题
自然的,会想统计数组中每个数字出现的次数,这里我使用了HashMap,HashMap中的getOrDefault方法真香。
拿出数字出现次数后,可以用一个HashSet来存,如果没有重复的,那么set和map的大小相同,如果重复,那么set会比map小。
class Solution {
public boolean uniqueOccurrences(int[] arr) {
//计算每个数的出现次数
Map<Integer,Integer> map=new HashMap<>();
for(int num:arr){
map.put(num,map.getOrDefault(num,0)+1);
}
//建set存数字
Set<Integer> set=new HashSet<>();
for(Map.Entry<Integer,Integer> entryset:map.entrySet()){
if(!set.contains(entryset.getValue()))
set.add(entryset.getValue());
}
return set.size()==map.size();
}
}