|
@@ -0,0 +1,67 @@
|
|
|
+package com.sf.leetcode;
|
|
|
+
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.LinkedList;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.Queue;
|
|
|
+
|
|
|
+/**
|
|
|
+ * tangzhenliang
|
|
|
+ */
|
|
|
+public class LRUCache1 {
|
|
|
+
|
|
|
+ private Queue<Integer> queue; // 利用队列 先进先出 特点 符合LRU 最长时间未使用 要求
|
|
|
+ private Map<Integer, Integer> map;
|
|
|
+ private int capacity;
|
|
|
+
|
|
|
+ public LRUCache1(int capacity) {
|
|
|
+ this.capacity = capacity;
|
|
|
+ queue = new LinkedList<>();
|
|
|
+ map = new HashMap<>();
|
|
|
+ }
|
|
|
+
|
|
|
+ public int get(int key) {
|
|
|
+ if (map.containsKey(key)) {
|
|
|
+ queue.remove(key); // 把之前的移除
|
|
|
+ queue.offer(key); // 重新放入队列 在队列尾部
|
|
|
+ return map.get(key);
|
|
|
+ } else {
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void put(int key, int value) {
|
|
|
+ if (map.containsKey(key)) {
|
|
|
+ queue.remove(key); // 如果存在 需要更改 则移除 重新放入队列尾部
|
|
|
+ }
|
|
|
+ else if (map.size() >= capacity) {
|
|
|
+ int key1 = queue.poll(); // 超出容量 则队列弹出 队列最前面的 则是长期未使用的
|
|
|
+ map.remove(key1);
|
|
|
+ }
|
|
|
+ map.put(key, value);
|
|
|
+ queue.offer(key);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public String toString() {
|
|
|
+ return "LRUCache1{" +
|
|
|
+ "queue=" + queue +
|
|
|
+ ", map=" + map +
|
|
|
+ ", capacity=" + capacity +
|
|
|
+ '}';
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void main(String[] args) {
|
|
|
+ LRUCache1 map = new LRUCache1(2);
|
|
|
+ map.put(1, 1);
|
|
|
+ map.put(2, 2);
|
|
|
+ System.out.println(map);
|
|
|
+ System.out.println(map.get(1));
|
|
|
+ System.out.println(map);
|
|
|
+ map.put(3, 3);
|
|
|
+ System.out.println(map);
|
|
|
+ System.out.println(map.get(2));
|
|
|
+ map.put(4, 4);
|
|
|
+ System.out.println(map);
|
|
|
+ }
|
|
|
+}
|