1. 程式人生 > >706,設計雜湊表對映

706,設計雜湊表對映

不使用任何內建的雜湊表庫設計一個雜湊對映

具體地說,你的設計應該包含以下的功能

  • put(key, value):向雜湊對映中插入(鍵,值)的數值對。如果鍵對應的值已經存在,更新這個值。
  • get(key):返回給定的鍵所對應的值,如果對映中不包含這個鍵,返回-1。
  • remove(key):如果對映中存在這個鍵,刪除這個數值對。

示例:

MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);          
hashMap.put(2, 2);         
hashMap.get(1);            // 返回 1
hashMap.get(3);            // 返回 -1 (未找到)
hashMap.put(2, 1);         // 更新已有的值
hashMap.get(2);            // 返回 1 
hashMap.remove(2);         // 刪除鍵為2的資料
hashMap.get(2);            // 返回 -1 (未找到) 

解法:很容易想到利用陣列下標和值來表示雜湊對映關係

java實現

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

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

C++實現

class MyHashMap { public:     /** Initialize your data structure here. */     MyHashMap() {         HashMap = vector<int> (1000001, -1);     }

    /** value will always be positive. */     void put(int key, int value) {         HashMap[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) {         return HashMap[key];     }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */     void remove(int key) {         HashMap[key] = -1;     } private:     vector<int> HashMap; };