题意:模拟实现LRU缓存,可以支持的功能有get(key)和set(key,value)
解法:
1、先来一个朴素的,自己模拟的双端队列,可惜TLE了,不过大家可以打打玩玩
public class LRUCache {
int capacity;
node head = null, tail = null;
public LRUCache(int capacity) {
this.capacity = capacity;
head = new node(-1, -1);
tail = new node(-1, -1);
head.next = tail;
tail.prev = head;
}
public int get(int key) {
node tot = head;
while (tot.key != key && tot != tail) {
tot = tot.next;
}
if (tot == tail) {
return -1;
} else {
int val = tot.val;
set(key, val);
return val;
}
}
public void set(int key, int value) {
node tot = head;
int cnt = 0;
while (tot.key != key && tot != tail) {
tot = tot.next;
cnt++;
}
if (tot == tail) {
tot = new node(key, value);
if (cnt == 1 + capacity) {
node temp = tail.prev;
temp.prev.next = tail;
tail.prev = temp.prev;
}
} else {
tot.val = value;
tot.prev.next = tot.next;
tot.next.prev = tot.prev;
}
node second = head.next;
head.next = tot;
tot.next = second;
tot.prev = head;
second.prev = tot;
}
public void print() {
node tot = head;
System.out.print("print : ");
while (tot != null) {
System.out.printf("<%d,%d> ", tot.key, tot.val);
tot = tot.next;
}
System.out.println();
}
public void reverse_print() {
node tot = tail;
System.out.print("reverse print : ");
while (tot != null) {
System.out.printf("<%d,%d> ", tot.key, tot.val);
tot = tot.prev;
}
System.out.println();
}
public static void main(String[] args) {
LRUCache lru = new LRUCache(1);
lru.set(2, 1);
lru.print();
lru.reverse_print();
System.out.println(lru.get(2));
lru.set(3, 2);
lru.print();
System.out.println(lru.get(2));
System.out.println(lru.get(3));
}
}
class node {
int key, val;
node prev = null, next = null;
node(int a, int b) {
key = a;
val = b;
}
}
2、下面的反应就是如何更快,第一反应是用HashCode来解决,介绍一个类LinkedHashMap——解决LRU的神奇啊
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache {
Map<Integer, Integer> map;
public LRUCache(int capacity) {
final int c = capacity;
map = new LinkedHashMap<Integer, Integer>(c, 0.75f, true) {
protected boolean removeEldestEntry(
Map.Entry<Integer, Integer> eldest) {
return size() > c;
}
};
}
public int get(int key) {
if (map.containsKey(key)) {
return map.get(key);
} else
return -1;
}
public void set(int key, int value) {
map.put(key, value);
}
public static void main(String[] args) {
LRUCache lru = new LRUCache(1);
lru.set(2, 1);
System.out.println(lru.get(2));
lru.set(3, 2);
System.out.println(lru.get(2));
System.out.println(lru.get(3));
}
}