706. Design HashMap
仅供自己学习
思路:
和705差不多,只是705是集合,这里是映射,区别就是存放的不止是key,而是key还有映射一个value,就相当于存放一个键值对,两个数据。
唯一不同就是判断的是是否有key值,是就覆盖当前value,无就加入这一个键值对。
代码:
1 class MyHashMap { 2 private: 3 vector<list<pair<int,int>>> data; 4 static const int base=769; 5 static int hash(int k){ 6 return k%base; 7 } 8 9 public: 10 /** Initialize your data structure here. */ 11 MyHashMap(): data(base){} 12 13 /** value will always be non-negative. */ 14 void put(int key, int value) { 15 int h=hash(key); 16 for(auto a=data[h].begin();a!=data[h].end();++a){ 17 if((*a).first==key){ 18 (*a).second=value; 19 return; 20 } 21 } 22 data[h].push_back(make_pair(key,value)); 23 } 24 25 /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ 26 int get(int key) { 27 int h=hash(key); 28 for(auto a=data[h].begin();a!=data[h].end();++a){ 29 if((*a).first==key){ 30 return (*a).second; 31 } 32 } 33 return -1; 34 } 35 36 /** Removes the mapping of the specified value key if this map contains a mapping for the key */ 37 void remove(int key) { 38 int h=hash(key); 39 for(auto a=data[h].begin();a!=data[h].end();++a){ 40 if((*a).first==key){ 41 data[h].erase(a); 42 return; 43 } 44 } 45 } 46 }; 47 48 /** 49 * Your MyHashMap object will be instantiated and called as such: 50 * MyHashMap* obj = new MyHashMap(); 51 * obj->put(key,value); 52 * int param_2 = obj->get(key); 53 * obj->remove(key); 54 */