设计hashmap,有两种方法,一种是拉链法,即每个索引下存放的是所有key的链表,另外一种是开放寻址法,当冲突是继续往下找。
一般设置数组的长度的时候,建议长度设置为质数。
class MyHashMap {public:/** Initialize your data structure here. */int N = 20011;vector<list<pair<int,int>>> p;MyHashMap() {p = vector<list<pair<int,int>>>(N);}list<pair<int,int>>::iterator find(int key){int t = key%N;for(auto it=p[t].begin();it!=p[t].end();it++){if(key==it->first){return it;}}return p[t].end();}/** value will always be non-negative. */void put(int key, int value) {int t = key%N;auto it = find(key);if(it==p[t].end()) {p[t].push_back(make_pair(key,value));}else it->second = 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 t = key%N;auto it = find(key);if(it==p[t].end()) return -1;else return it->second;}/** Removes the mapping of the specified value key if this map contains a mapping for the key */void remove(int key) {int t = key%N;auto it = find(key);if(it!=p[t].end()) {p[t].erase(it);}}};/*** 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);*/
