獨一無二的出現次數
版本1:
優點:耗空間少、可拓展性強
缺點:時間開銷大一點
class Solution {
public:
unordered_map<int,int> m;
unordered_set<int> vis;
bool uniqueOccurrences(vector<int>& arr) {
for(int x:arr){
m[x]++;
}
for(unordered_map<int,int>::iterator it = m.begin();it!=m.end();it++){
if(vis.count(it->second)){
return false;
}
vis.insert(it->second);
}
return true;
}
};
版本2:
由於已給數據保證在,我們就設計
,然後使用數組就可,避免了map的使用。
class Solution {
public:
int cnt[2010] = {0};
bool vis[1010] = {0};
bool uniqueOccurrences(vector<int>& arr) {
for(int x:arr){
cnt[x+1001]++;
}
for(int x:cnt){
if(vis[x]){
return false;
}
if(x){
vis[x] = true;;
}
}
return true;
}
};