146.LRU-Cache
146. LRU Cache
题目地址
https://www.lintcode.com/problem/lru-cache
https://leetcode.com/problems/lru-cache/
题目描述
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Finally, you need to return the data from each get.
代码
class LRUCache {
private class Node {
Node prev, next;
int val, key;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
private int capacity;
private HashMap<Integer, Node> map = new HashMap<>();
private Node head = new Node(-1, -1);
private Node tail = new Node(-1, -1);
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
} else {
Node node = map.get(key);
node.prev.next = node.next;
node.next.prev = node.prev;
moveToTail(node);
return node.val;
}
}
public void put(int key, int value) {
if (map.get(key) != -1) {
map.get(key).val = value;
} else {
if (map.size() >= capacity) {
map.remove(head.next.key);
head.next = head.next.next;
head.next.prev = head;
}
Node node = new Node(key, value);
map.put(key, node);
moveToTail(node);
}
}
private void moveToTail(Node node) {
tail.prev.next = node;
node.prev = tail.prev;
node.next = tail;
tail.prev = node;
}
}
Last updated