Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
如果数组中每个数字出现的次数都是不同的,返回true,
但凡有相同的次数,返回false.
思路:
看现有的次数是否在已有的次数中出现,考虑用hashSet.
但是这里不想用hashmap来记录每个数字出现的次数,
那么可以把数组排序,这样可以方便统计次数。
不要忘了最后一个次数。
public boolean uniqueOccurrences(int[] arr) {
int cnt = 1;
HashSet<Integer> set = new HashSet<>();
Arrays.sort(arr);
for(int i = 1; i < arr.length; i++) {
if(arr[i] == arr[i-1]) {
cnt ++;
} else {
if(set.contains(cnt)) return false;
set.add(cnt);
cnt = 1;
}
}
if(set.contains(cnt)) return false;
return true;
}
该博客主要讨论如何检查给定整数数组中每个元素出现的次数是否唯一。通过排序数组,逐个比较相邻元素,统计相同元素的出现次数,并利用HashSet来检查这些次数是否已经存在。如果发现重复的计数,则返回false,否则返回true。这种方法避免了使用HashMap来直接计算每个元素的频率,而是通过排序和迭代实现了功能。
405

被折叠的 条评论
为什么被折叠?



