您的位置:首页 > 编程语言 > Go语言

LRU Cache

2014-01-27 07:28 447 查看
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.

solution:

using double linked list + hashMap<key, ListNode>

public class LRUCache {

Map<Integer, ListNode> map;
ListNode head, tail;
int capacity, size;

public LRUCache(int capacity){
map = new HashMap<>(capacity);
head = new ListNode(0,0);
tail = new ListNode(0,0);
head.next = tail;
tail.pre = head;
this.capacity = capacity;
this.size = size;
}

public int get(int key){
if(!map.containsKey(key)) return -1;
remove(map.get(key));
insert(map.get(key));
return map.get(key).val;
}

public void set(int key, int value){
if(map.containsKey(key)){
map.get(key).val = value;
remove(map.get(key));
insert(map.get(key));
}else{
if(size >= capacity){
map.remove(tail.pre.key);
remove(tail.pre);
}
ListNode newNode = new ListNode(key,value);
map.put(key,newNode);
insert(newNode);
}
}

private void remove(ListNode node){
if(node == null) return;
node.pre.next = node.next;
node.next.pre = node.pre;
size --;
}

private void insert(ListNode node){
if(node == null) return;
node.next = head.next;
head.next.pre = node;
node.pre = head;
head.next = node;
size++;
}

private class ListNode {
int key, val;
ListNode next;
ListNode pre;

ListNode(int key, int val) {
this.val = val;
this.key = key;
next = null;
pre = null;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm