Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.int get(int key) Return the value of the key if the key exists, otherwise return -1.void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.The functions get and put must each run in O(1) average time complexity.
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
In this approach, we use a doubly linked list to maintain the order of use of the cache and a HashMap for quick access to elements. The doubly linked list maintains a list of nodes, each representing a key-value pair. The head of the list is the most recently used, and the tail is the least used.
get and put operations due to the constant time for hash table and linked list operations.The second approach involves the same data structures but focuses on optimizing memory usage and cleaning up code for efficiency.
Key Differences:
get and put operations as we continue to have constant time hash table and linked list operations.