|
| 1 | +https://leetcode.com/problems/lru-cache/ |
| 2 | + |
1 | 3 | LRU,全称Least Recently Used,最近最少使用缓存。 |
2 | 4 |
|
3 | 5 | ```java |
4 | 6 | import java.util.HashMap; |
5 | 7 | import java.util.LinkedList; |
6 | 8 |
|
7 | | -public class LRUCache2 { |
| 9 | +class LRUCache { |
8 | 10 | private HashMap<Integer, Integer> cacheMap = new HashMap<>(); |
9 | 11 | private LinkedList<Integer> recentlyList = new LinkedList<>(); |
10 | 12 | private int capacity; |
11 | 13 |
|
12 | | - public LRUCache2(int capacity) { |
| 14 | + public LRUCache(int capacity) { |
13 | 15 | this.capacity = capacity; |
14 | 16 | } |
15 | 17 |
|
16 | | - private int get(int key) { |
| 18 | + public int get(int key) { |
17 | 19 | if (!cacheMap.containsKey(key)) { |
18 | 20 | return -1; |
19 | 21 | } |
20 | | - |
21 | 22 | recentlyList.remove((Integer) key); |
22 | 23 | recentlyList.add(key); |
23 | | - |
24 | 24 | return cacheMap.get(key); |
25 | 25 | } |
26 | 26 |
|
27 | | - private void put(int key, int value) { |
| 27 | + public void put(int key, int value) { |
28 | 28 | if (cacheMap.containsKey(key)) { |
29 | 29 | recentlyList.remove((Integer) key); |
30 | | - } |
31 | | - |
32 | | - if (cacheMap.size() == capacity) { |
| 30 | + }else if(cacheMap.size() == capacity){ |
33 | 31 | cacheMap.remove(recentlyList.removeFirst()); |
34 | 32 | } |
35 | | - |
36 | | - cacheMap.put(key, value); |
37 | 33 | recentlyList.add(key); |
38 | | - |
| 34 | + cacheMap.put(key, value); |
39 | 35 | } |
40 | 36 |
|
41 | 37 | public static void main(String[] args) { |
|
0 commit comments