设计hashmap,有两种方法,一种是拉链法,即每个索引下存放的是所有key的链表,另外一种是开放寻址法,当冲突是继续往下找。
    一般设置数组的长度的时候,建议长度设置为质数。

    1. class MyHashMap {
    2. public:
    3. /** Initialize your data structure here. */
    4. int N = 20011;
    5. vector<list<pair<int,int>>> p;
    6. MyHashMap() {
    7. p = vector<list<pair<int,int>>>(N);
    8. }
    9. list<pair<int,int>>::iterator find(int key){
    10. int t = key%N;
    11. for(auto it=p[t].begin();it!=p[t].end();it++){
    12. if(key==it->first){
    13. return it;
    14. }
    15. }
    16. return p[t].end();
    17. }
    18. /** value will always be non-negative. */
    19. void put(int key, int value) {
    20. int t = key%N;
    21. auto it = find(key);
    22. if(it==p[t].end()) {
    23. p[t].push_back(make_pair(key,value));
    24. }
    25. else it->second = value;
    26. }
    27. /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    28. int get(int key) {
    29. int t = key%N;
    30. auto it = find(key);
    31. if(it==p[t].end()) return -1;
    32. else return it->second;
    33. }
    34. /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    35. void remove(int key) {
    36. int t = key%N;
    37. auto it = find(key);
    38. if(it!=p[t].end()) {
    39. p[t].erase(it);
    40. }
    41. }
    42. };
    43. /**
    44. * Your MyHashMap object will be instantiated and called as such:
    45. * MyHashMap* obj = new MyHashMap();
    46. * obj->put(key,value);
    47. * int param_2 = obj->get(key);
    48. * obj->remove(key);
    49. */