-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest55.java
More file actions
54 lines (47 loc) · 1.21 KB
/
test55.java
File metadata and controls
54 lines (47 loc) · 1.21 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 byteDance;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @Author:lizeyang
* @Date:2020/5/23 17:13
* function:LRU实现,美团面试耻辱!!!
*/
public class test55 {
//方法一:LinkedhashMap实现
int capacity;
Map<Integer, Integer> map;
test55(int capacity) {
this.capacity = capacity;
map = new LinkedHashMap<Integer, Integer>();
}
public void put(int key, int value) {
if (map.containsKey(key)) {
map.remove(key);
map.put(key, value);
return;
}
map.put(key, value);
if (map.size() > capacity) {
map.remove(map.entrySet().iterator().next().getKey());
}
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
int value = map.remove(key);
map.put(key, value);
return value;
}
public static void main(String[] args) {
test55 test = new test55(3);
test.put(1,2);
test.put(2,3);
test.put(3,4);
test.put(4,5);
System.out.println(test.get(2));
test.put(5,6);
System.out.println(test.get(2));
}
//方法二见test56
}