解题思路
1207. 独一无二的出现次数
该题主要找到每个数值出现的次数,思路如下:
①可以先使用一个哈希表存入每个数值及其出现的次数;
②然后再用一个哈希表单独存放各数值出现的次数,存入的过程中如果发现有相同的次数,就返回false,否则不存在相同的次数,那么就返回true。
代码
class Solution {
//哈希表
public static boolean uniqueOccurrences(int[] arr) {
//把数组中的数值及其出现的次数存入哈希表map中
Map<Integer , Integer> map = new HashMap<>();
for (int value : arr) {
map.put(value, map.getOrDefault(value, 0)+1);
}
//把次数放出哈希表countSet中,看是否有重复的次数
Set<Integer> countSet = new HashSet<>();
//遍历哈希表map中的value:次数
for(Integer value : map.values()) {
if(countSet.contains(value)) {
return false;
}
countSet.add(value);
}
return true;
}
}
来自评论区大佬的代码:
思路是相同的,利用了HashSet的构造方法,直接检查了是否有重复的次数。
counter.values() :把哈希表中的value返回成一个集合
Collection<Integer> c = counter.values();
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> counter = new HashMap<>();
for (int elem : arr)
counter.put(elem, counter.getOrDefault(elem, 0) + 1);
return counter.size() == new HashSet<Integer>(counter.values()).size();
}