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;
}