-
Notifications
You must be signed in to change notification settings - Fork 0
/
146 LRU Cache.java
40 lines (35 loc) · 917 Bytes
/
146 LRU Cache.java
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
class LRUCache {
int capacity;
int[] pair = new int[3001];
LinkedList<Integer> cache = new LinkedList<>();
public LRUCache(int capacity) {
this.capacity = capacity;
Arrays.fill(pair, -1);
}
public int get(int key) {
int value = pair[key];
if (value != -1) {
cache.remove((Integer)key);
cache.addFirst(key);
}
return value;
}
public void put(int key, int value) {
if (get(key) != -1) {
pair[key] = value;
return;
}
if (cache.size() >= capacity) {
pair[cache.getLast()] = -1;
cache.removeLast();
}
cache.addFirst(key);
pair[key] = value;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/