Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
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
Constraints:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
这题题意是让我们求出是否给定的数组中,每个数字出现的次数都是唯一的。
我这里先排序,然后遍历一次,当数字发生变更的时候,记录下前一串相同数字的出现次数,当次数存在的时候,直接返回false即可。
需要注意的是,最后还需要判断一下,因为最后一个数不会出发判断的逻辑,需要额外判断。
class UniqueNumberofOccurrences : public Solution {
public:
void Exec() {
}
bool uniqueOccurrences(vector<int>& arr) {
std::sort(arr.begin(), arr.end());
std::set<int> occurrences;
int count = 0, prev = 0;
for (int i = 0; i < arr.size(); i++) {
if (i == 0 || arr[i] == prev) {
count++;
} else {
auto it = occurrences.find(count);
if (it != occurrences.end()) {
return false;
}
occurrences.insert(count);
count = 1;
}
prev = arr[i];
}
return occurrences.find(count) == occurrences.end();
}
};