forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache_146.java
More file actions
54 lines (50 loc) · 1.29 KB
/
LRUCache_146.java
File metadata and controls
54 lines (50 loc) · 1.29 KB
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
package LeetCode;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @Classname LRUCache_146
* @Description LRU算法的实现,输入一个容器,当超过了移除最近最少使用的,
* cache.put(1, 1);
* cache.put(2, 2);
* 输入的key是任务的名字Map.entity
*
* 维护一个队列
*
*
* @Date 19-5-20 下午4:15
* @Created by mao<[email protected]>
*/
public class LRUCache_146 {
Map<Integer,Integer> map = new LinkedHashMap<>();
int capacity=0;
public LRUCache_146(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if(map.containsKey(key)){
int value = map.get(key);
map.remove(key);
map.put(key,value);
return value;
}else{
return -1;
}
}
public void put(int key, int value) {
if(capacity <= 0) return;
if(map.containsKey(key)){
map.remove(key);
map.put(key,value);
return;
}
if(map.size() == capacity){
Map.Entry<Integer,Integer> entry = map.entrySet().iterator().next();
if(entry!=null){
map.remove(entry.getKey());
map.put(key,value);
}
}else{
map.put(key,value);
}
}
}