[Leetcode] 706.デザイン-ハッシュマップ(シミュレーション)[シンプル]

リンク

https://leetcode-cn.com/problems/design-hashmap/

時間がかかる

問題解決:13分
問題解決:8分

題名

組み込みのハッシュテーブルライブラリを使用せずにハッシュマップ(HashMap)を設計します。

MyHashMapクラスを実装します。

  • MyHashMap()は、空のマップでオブジェクトを初期化します
  • void put(int key、int value)キーと値のペア(key、value)をHashMapに挿入します。キーがマップにすでに存在する場合は、対応する値の値を更新します。
  • int get(int key)特定のキーによってマップされた値を返します。マッピングにキーマッピングが含まれていない場合は、-1を返します。
  • void remove(key)マッピングにキーマッピングがある場合は、キーとそれに対応する値を削除します。

促す:

  • 0 <=キー、値<= 1 0 6 10 ^ 61 06
  • 1 0 4 10 ^ 4まで呼び出す1 04メソッドの配置、取得、削除

アイデア

チェーンアドレスメソッド:ハッシュ関数x%base、put()は最初にハッシュ値のリンクリストを検索し、更新された値を見つけ、見つからない場合はペアを追加します。get()はハッシュ値のリンクリストを検索します。 find it戻り値、それ以外の場合は-1を返します。remove()はハッシュ値のリンクリストを調べ、見つかった場合はこの位置にある要素ペアを削除し、直接戻ります。

時間計算量:O(n / b)O(n / b)O n / b 一様分布を仮定すると、n個のデータ、b個のリンクリストにはデータがあります

ACコード

class MyHashMap {
    
    
private:
    vector<list<pair<int, int>>> data;
    int base = 769;                                    
public:
    int hash(int x) {
    
    
        return x % base;
    }                              
                                        
    /** Initialize your data structure here. */
    MyHashMap() {
    
    
        data.resize(base);
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
    
    
        int h = hash(key);
        for(auto it = data[h].begin(); it != data[h].end(); ++it) {
    
    
            if(it->first == key) {
    
    
                it->second = value;
                return ;
            }
        }
        data[h].push_back(make_pair(key, value));
    }
    
    /** 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) {
    
    
        int h = hash(key);
        for(auto x : data[h]) {
    
    
            if(x.first == key) return x.second;      
        }
        return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
    
    
        int h = hash(key);
        for(auto it = data[h].begin(); it != data[h].end(); ++it) {
    
    
            if(it->first == key) {
    
    
                data[h].erase(it);
                return ;
            }
        }
    }
};

/**
 * 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);
 */

おすすめ

転載: blog.csdn.net/Krone_/article/details/114784696