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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章