2020-01-02【Leetcode-探索-哈希表】

设计哈希集合

参考做法

class MyHashSet {
    static const int SIZE = 1997;
    vector<vector<int>> table = vector<vector<int>>(SIZE);
public:
    /** Initialize your data structure here. */
    MyHashSet() {
    }
    
    void add(int key) {
        auto &v = table[key % SIZE];
        for(auto i: v){
            if(i == key){
                return;
            }
        }
        v.push_back(key);
    }
    
    void remove(int key) {
        auto &v = table[key % SIZE];
        int i = 0;
        int vSize = v.size();
        for(i = 0; i < vSize; i++){
            if(v[i] == key){
                break;
            }
        }
        if(i == vSize){
            return;
        }
        int j = i;
        i++;
        while(i < vSize){
            v[j++] = v[i++];
        }
        if(!v.empty()){
            v.pop_back();
        }
    }
    
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
        auto &v = table[key % SIZE];
        for(auto i: v){
            if(i == key){
                return true;
            }
        }
        return false;
    }
};

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet* obj = new MyHashSet();
 * obj->add(key);
 * obj->remove(key);
 * bool param_3 = obj->contains(key);
 */

设计哈希映射

参考做法

class MyHashMap {
public:
    /** Initialize your data structure here. */
    int a[100000];
    int b[100000]={0};
    MyHashMap() {
        
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
        a[key]=value;
        b[key]=1;
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        if(b[key]==0)return -1;
        else return a[key];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        if(b[key]==1){
            a[key]=0;
            b[key]=0;
        }
    }
};

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap* obj = new MyHashMap();
 * obj->put(key,value);
 * int param_2 = obj->get(key);
 * obj->remove(key);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值