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.
思路:用HashMap和双向链表来实现
参考:http://www.programcreek.com/2013/03/leetcode-lru-cache-java/
java代码:
- public class LRUCache {
- Map<Integer,LinkNode> mp = new HashMap<Integer,LinkNode>();
- int capacity;
- LinkNode head;
- LinkNode tail;
- int cur;
- public LRUCache(int capacity) {
- this.capacity = capacity;
- cur = 0;
- head = null;
- tail = null;
- }
- void moveToHead(LinkNode p) {
- p.next = head;
- p.pre = null;
- if(head!=null) {
- head.pre = p;
- }
- head = p;
- if(tail == null) {
- tail = p;
- }
- }
- void removeNode(LinkNode p) {
- LinkNode curNode = p;
- LinkNode preNode = p.pre;
- LinkNode nextNode = p.next;
- if(preNode!=null) {
- preNode.next = nextNode;
- } else {
- head = nextNode;
- }
- if(nextNode!=null) {
- nextNode.pre = preNode;
- } else {
- tail = preNode;
- }
- }
- public int get(int key) {
- if(mp.containsKey(key)) {
- LinkNode p = mp.get(key);
- removeNode(p);
- moveToHead(p);
- return p.value;
- } else {
- return -1;
- }
- }
- public void set(int key, int value) {
- if(mp.containsKey(key)) {
- LinkNode p = mp.get(key);
- removeNode(p);
- p.value = value;
- moveToHead(p);
- } else {
- LinkNode p = new LinkNode(key,value);
- if(cur==capacity) {
- mp.remove(tail.key);
- tail = tail.pre;
- if(tail!=null) tail.next = null;
- moveToHead(p);
- mp.put(key,p);
- } else {
- moveToHead(p);
- mp.put(key,p);
- cur++;
- }
- }
- }
- }
- class LinkNode{
- public int key;
- public int value;
- public LinkNode pre;
- public LinkNode next;
- public LinkNode(int key,int value) {
- this.key = key;
- this.value = value;
- pre = null;
- next = null;
- }
- }

浙公网安备 33010602011771号