通过简单的单元测试通过 leetcode 问题的测试的实现
我已经在以下位置提出了一个拉取请求:https://github.com/haoel/leetcode/pull/90/files 代码后来在答案中得到了改进,我没有费心再提出另一个拉取请求,所以这里的代码现在稍微好一些。accessOrder = true
LRUCache.java
import java.util.Iterator;
import java.util.LinkedHashMap;
public class LRUCache {
private int capacity;
private LinkedHashMap<Integer,Integer> map;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new LinkedHashMap<>(16, 0.75f, true);
}
public int get(int key) {
Integer value = this.map.get(key);
if (value == null) {
value = -1;
}
return value;
}
public void put(int key, int value) {
if (
!this.map.containsKey(key) &&
this.map.size() == this.capacity
) {
Iterator<Integer> it = this.map.keySet().iterator();
it.next();
it.remove();
}
this.map.put(key, value);
}
}
LRUCacheTest.java
public class LRUCacheTest {
public static void main(String[] args) {
LRUCache c;
// Starts empty.
c = new LRUCache(2);
assert c.get(1) == -1;
// Below capcity.
c = new LRUCache(2);
c.put(1, 1);
assert c.get(1) == 1;
assert c.get(2) == -1;
c.put(2, 4);
assert c.get(1) == 1;
assert c.get(2) == 4;
// Above capacity, oldest is removed.
c = new LRUCache(2);
c.put(1, 1);
c.put(2, 4);
c.put(3, 9);
assert c.get(1) == -1;
assert c.get(2) == 4;
assert c.get(3) == 9;
// get renews entry
c = new LRUCache(2);
c.put(1, 1);
c.put(2, 4);
assert c.get(1) == 1;
c.put(3, 9);
assert c.get(1) == 1;
assert c.get(2) == -1;
assert c.get(3) == 9;
// Double put does not remove due to capacity.
c = new LRUCache(2);
assert c.get(2) == -1;
c.put(2, 6);
assert c.get(1) == -1;
c.put(1, 5);
c.put(1, 2);
assert c.get(1) == 2;
assert c.get(2) == 6;
}
}
removeEldestEntry()
alternative implementation
不确定它是否值得,因为它需要相同数量的行,但这里是为了完整性:
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Map;
import java.io.*;
class LinkedhashMapWithCapacity<K,V> extends LinkedHashMap<K,V> {
private int capacity;
public LinkedhashMapWithCapacity(int capacity) {
super(16, 0.75f, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return this.size() > this.capacity;
}
}
public class LRUCache {
private LinkedhashMapWithCapacity<Integer,Integer> map;
public LRUCache(int capacity) {
this.map = new LinkedhashMapWithCapacity<>(capacity);
}
public int get(int key) {
Integer value = this.map.get(key);
if (value == null) {
value = -1;
}
return value;
}
public void put(int key, int value) {
this.map.put(key, value);
}
}
在 Ubuntu 20.10、OpenJDK 11.0.10 上测试。