-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLRUCache.java
More file actions
52 lines (44 loc) · 887 Bytes
/
LRUCache.java
File metadata and controls
52 lines (44 loc) · 887 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
*
*/
package cc.dectinc.leetcode;
import java.util.LinkedHashMap;
/**
* @author Dectinc
* @version Apr 15, 2015 6:33:59 PM
*
*/
public class LRUCache {
private final LinkedHashMap<Integer, Integer> map;
private final int capacity;
public LRUCache(int capacity) {
this.map = new LinkedHashMap<Integer, Integer>();
this.capacity = capacity;
}
public int get(int key) {
Integer result = map.get(key);
if (result == null) {
return -1;
}
map.remove(key);
map.put(key, result);
return result;
}
public void set(int key, int value) {
Integer result = map.get(key);
if (result == null) {
if (map.size() == capacity) {
map.remove(map.keySet().iterator().next());
}
} else {
map.remove(key);
}
map.put(key, value);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}