|
| 1 | +// Runtime: 105 ms (Top 72.29%) | Memory: 61.60 MB (Top 55.94%) |
| 2 | + |
1 | 3 | class MyHashMap {
|
| 4 | + vector<vector<pair<int, int>>> map; |
| 5 | + const int size = 10000; |
2 | 6 | public:
|
3 |
| - vector<pair<int,int>> mpp; |
4 |
| - MyHashMap() { |
5 |
| - |
6 |
| - } |
7 |
| - |
8 |
| - void put(int key, int value) { |
9 |
| - for(int i=0;i<mpp.size();i++){ |
10 |
| - if(mpp[i].first==key){ |
11 |
| - mpp[i].second=value; |
12 |
| - break; |
| 7 | + /** Initialize your data structure here. */ |
| 8 | + MyHashMap() { |
| 9 | + map.resize(size); |
| 10 | + } |
| 11 | + |
| 12 | + /** value will always be non-negative. */ |
| 13 | + void put(int key, int value) { |
| 14 | + int index = key % size; |
| 15 | + vector<pair<int, int>> &row = map[index]; |
| 16 | + for(auto iter = row.begin(); iter != row.end(); iter++) |
| 17 | + { |
| 18 | + if(iter->first == key) |
| 19 | + { |
| 20 | + iter->second = value; |
| 21 | + return; |
13 | 22 | }
|
14 | 23 | }
|
15 |
| - mpp.push_back({key,value}); |
16 |
| - } |
17 |
| - |
18 |
| - int get(int key) { |
19 |
| - for(int i=0;i<mpp.size();i++){ |
20 |
| - if(mpp[i].first==key && mpp[i].second!=INT_MIN)return mpp[i].second; |
21 |
| - } |
22 |
| - return -1; |
23 |
| - } |
24 |
| - |
25 |
| - void remove(int key) { |
26 |
| - for(int i=0;i<mpp.size();i++){ |
27 |
| - if(mpp[i].first==key)mpp[i].second=INT_MIN; |
28 |
| - } |
29 |
| - } |
| 24 | + row.push_back(make_pair(key, value)); |
| 25 | + } |
| 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 index = key % size; |
| 30 | + vector<pair<int, int>> &row = map[index]; |
| 31 | + for (auto iter = row.begin(); iter != row.end(); iter++) |
| 32 | + { |
| 33 | + if (iter->first == key) |
| 34 | + { |
| 35 | + return iter->second; |
| 36 | + } |
| 37 | + } |
| 38 | + return -1; |
| 39 | + } |
| 40 | + |
| 41 | + /** Removes the mapping of the specified value key if this map contains a mapping for the key */ |
| 42 | + void remove(int key) { |
| 43 | + int index = key % size; |
| 44 | + vector<pair<int, int>> &row = map[index]; |
| 45 | + for (auto iter = row.begin(); iter != row.end(); iter++) |
| 46 | + { |
| 47 | + if (iter->first == key) |
| 48 | + { |
| 49 | + row.erase(iter); |
| 50 | + return; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
30 | 54 | };
|
| 55 | + |
| 56 | +/** |
| 57 | + * Your MyHashMap object will be instantiated and called as such: |
| 58 | + * MyHashMap* obj = new MyHashMap(); |
| 59 | + * obj->put(key,value); |
| 60 | + * int param_2 = obj->get(key); |
| 61 | + * obj->remove(key); |
| 62 | + */ |
0 commit comments