leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0706.cpp (808B)


      1 class MyHashMap {
      2     const int mod = 9973;
      3 
      4     vector<vector<pair<int, int>>> hm;
      5     int hash(int key) { return key % mod; }
      6 
      7     int &find(int key) {
      8         static int err = -1;
      9         for (auto &[k, v] : hm[hash(key)])
     10             if (k == key) return v;
     11         return err;
     12     }
     13 
     14   public:
     15     MyHashMap() : hm(mod) {}
     16     void put(int key, int value) {
     17         int &loc = find(key);
     18         if (loc == -1)
     19             hm[hash(key)].push_back({key, value});
     20         else
     21             loc = value;
     22     }
     23     int get(int key) { return find(key); }
     24     void remove(int key) {
     25         vector<pair<int, int>> &row = hm[hash(key)];
     26         for (int i = 0; i < row.size(); i++)
     27             if (row[i].first == key) {
     28                 row.erase(row.begin() + i);
     29                 break;
     30             }
     31     }
     32 };