1207. 独一无二的出现次数(面试题打卡/哈希/简单)
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/unique-number-of-occurrences
题干:
给你一个整数数组 arr
,请你帮忙统计数组中每个数的出现次数。
如果每个数的出现次数都是独一无二的,就返回 true
;否则返回 false
。
提示:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
示例:
输入:arr = [1,2,2,1,1,3]
输出:true
解释:在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。
输入:arr = [1,2]
输出:false
题解:
方法一:直接使用哈希表
- 使用map记录每个数组出现的次数
- 次数存放到set中去重
- map和set的大小一样,则说明没有重复的,否则重复
class Solution {
public boolean uniqueOccurrences(int[] arr) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int x : arr) {
hashMap.put(x, hashMap.getOrDefault(x, 0) + 1); // key--数组中的元素 value--次数
}
HashSet<Integer> hashSet = new HashSet<>(); // 去重
hashSet.addAll(hashMap.values());
return hashMap.size() == hashSet.size(); // 比较大小即可
}
}
方法二:使用数组模拟哈希
- cnts数组记录次数
- st数组判断次数是否重复
class Solution {
public boolean uniqueOccurrences(int[] arr) {
// 统计次数
int[] cnts = new int[2010];
for (int x : arr) {
cnts[x + 1000]++;
}
// 判断次数是否唯一
boolean[] st = new boolean[2010];
for (int cnt : cnts) {
if (cnt != 0) {
if (st[cnt]) return false; // 不唯一,false
else st[cnt] = true;
}
}
return true;
}
}