-
Notifications
You must be signed in to change notification settings - Fork 1
/
146. LRU Cache.java
70 lines (50 loc) · 1.42 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//https://leetcode.com/problems/lru-cache/solutions/4322888/easiest-approach-using-hashmap-and-deque/
class LRUCache {
Deque<Integer> deque = new ArrayDeque<>();
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int capacity = 0;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if(map.containsKey(key))
{
deque.remove(key);
deque.addFirst(key);
return map.getOrDefault(key,-1);
}
else
{
return -1;
}
}
public void put(int key, int value) {
if(map.containsKey(key))
{
map.put(key,value);
deque.remove(key);
deque.addFirst(key);
}
else
{
if(deque.size()<capacity)
{
deque.addFirst(key);
map.put(key,value);
}
else
{
map.remove(deque.getLast());
deque.removeLast();
deque.addFirst(key);
map.put(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);
*/