- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 47 lines of Java from the credited upstream file 146.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Node {2 public int key;3 public int value;4 public Node(int key, int value) {5 this.key = key;6 this.value = value;7 }8}9 10class LRUCache {11 public LRUCache(int capacity) {12 this.capacity = capacity;13 }14 15 public int get(int key) {16 if (!keyToNode.containsKey(key))17 return -1;18 19 Node node = keyToNode.get(key);20 cache.remove(node);21 cache.add(node);22 return node.value;23 }24 25 public void put(int key, int value) {26 if (keyToNode.containsKey(key)) {27 keyToNode.get(key).value = value;28 get(key);29 return;30 }31 32 if (cache.size() == capacity) {33 Node lastNode = cache.iterator().next();34 cache.remove(lastNode);35 keyToNode.remove(lastNode.key);36 }37 38 Node node = new Node(key, value);39 cache.add(node);40 keyToNode.put(key, node);41 }42 43 private int capacity;44 private Set<Node> cache = new LinkedHashSet<>();45 private Map<Integer, Node> keyToNode = new HashMap<>();46}47