|
@@ -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;
|
|
|
|
+ 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);
|
|
|
|
+ }
|
|
|
|
+}
|