LeetCode 1207. 獨一無二的出現次數 (STL庫 || 自己hash函數、數組映射)

獨一無二的出現次數
版本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:
由於已給數據保證在[1000,1000][-1000,1000],我們就設計
Hash(x)=x+1010Hash(x) = x+1010,然後使用數組就可,避免了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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章