vivek_ragi

DESIGN_HASHMAP

Jun 29th, 2021
453
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class MyHashMap {
  2. public:
  3.     /** Initialize your data structure here. */
  4.     vector<pair<int,int>> v;
  5.     MyHashMap() {
  6.         v.clear();
  7.     }
  8.    
  9.     /** value will always be non-negative. */
  10.     void put(int key, int value) {
  11.         int flag = 0;
  12.         if(v.size() == 0) {
  13.             v.push_back({key,value});
  14.         }
  15.         else {
  16.             for(int i = 0; i < v.size(); ++i) {
  17.                 if(v[i].first == key) {
  18.                     flag = 1;
  19.                     v[i].second = value;
  20.                     break;
  21.                 }
  22.  
  23.             }
  24.         }
  25.        
  26.         if(flag == 0 and v.size()!= 0)
  27.         v.push_back({key,value});
  28.     }
  29.    
  30.     /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
  31.     int get(int key) {
  32.         for(int i = 0; i < v.size(); ++i) {
  33.             if(v[i].first == key) {
  34.                 return v[i].second;
  35.             }
  36.         }
  37.         return -1;
  38.     }
  39.    
  40.     /** Removes the mapping of the specified value key if this map contains a mapping for the key */
  41.     void remove(int key) {
  42.         for(auto i = v.begin(); i != v.end(); ++i) {
  43.             if(i ->first == key) {
  44.                 v.erase(i);
  45.             }
  46.         }
  47.     }
  48. };
  49.  
  50. /**
  51.  * Your MyHashMap object will be instantiated and called as such:
  52.  * MyHashMap* obj = new MyHashMap();
  53.  * obj->put(key,value);
  54.  * int param_2 = obj->get(key);
  55.  * obj->remove(key);
  56.  */
RAW Paste Data