Advertisement
1988coder

460. LFU Cache

Dec 9th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. /*
  2. Time Complexity of all operations is O(1)
  3. Space Complexity: O(capacity)
  4. */
  5. class LFUCache {
  6.     HashMap<Integer, Integer> keyValueMap;
  7.     HashMap<Integer, Integer> keyCountMap;
  8.     HashMap<Integer, LinkedHashSet<Integer>> countKeysMap;
  9.     int maxCapacity;
  10.     int curMin;
  11.    
  12.     public LFUCache(int capacity) {
  13.         keyValueMap = new HashMap<Integer, Integer>();
  14.         keyCountMap = new HashMap<Integer, Integer>();
  15.         countKeysMap = new HashMap<Integer, LinkedHashSet<Integer>>();
  16.         maxCapacity = capacity;
  17.         curMin = -1;
  18.     }
  19.    
  20.     public int get(int key) {
  21.         if (!keyValueMap.containsKey(key)) {
  22.             return -1;
  23.         }
  24.         int curCount = keyCountMap.get(key);
  25.         keyCountMap.put(key, curCount+1);
  26.         countKeysMap.get(curCount).remove(key);
  27.         if (curMin == curCount && countKeysMap.get(curCount).isEmpty()) {
  28.             curMin++;
  29.             countKeysMap.remove(curCount);
  30.         }
  31.         addKeyToCountKeysMap(curCount+1, key);
  32.         return keyValueMap.get(key);
  33.     }
  34.    
  35.     public void put(int key, int value) {
  36.         if (maxCapacity <= 0) {
  37.             return;
  38.         }
  39.         if (keyValueMap.containsKey(key)) {
  40.             keyValueMap.put(key, value);
  41.             get(key);
  42.             return;
  43.         }
  44.        
  45.         if (keyValueMap.size() == maxCapacity) {
  46.             int toBeRemoved = countKeysMap.get(curMin).iterator().next();
  47.             countKeysMap.get(curMin).remove(toBeRemoved);
  48.             if (countKeysMap.get(curMin).isEmpty()) {
  49.                 countKeysMap.remove(curMin);
  50.             }
  51.             keyValueMap.remove(toBeRemoved);
  52.             keyCountMap.remove(toBeRemoved);
  53.         }
  54.         keyValueMap.put(key, value);
  55.         keyCountMap.put(key, 1);
  56.         curMin = 1;
  57.         addKeyToCountKeysMap(1, key);
  58.     }
  59.    
  60.     private void addKeyToCountKeysMap(int count, int key) {
  61.         if (!countKeysMap.containsKey(count)) {
  62.             countKeysMap.put(count, new LinkedHashSet<Integer>());
  63.         }
  64.         countKeysMap.get(count).add(key);
  65.     }
  66. }
  67.  
  68. /**
  69.  * Your LFUCache object will be instantiated and called as such:
  70.  * LFUCache obj = new LFUCache(capacity);
  71.  * int param_1 = obj.get(key);
  72.  * obj.put(key,value);
  73.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement