解法
package com.wangxiaohu;import java.util.LinkedHashMap;public class LeetCode146 {
class LRUCache {
private int size;LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>();public LRUCache(int capacity) {
this.size = capacity;}public int get(int key) {
if (!cache.containsKey(key)) {
return -1;}makeKeyRecently(key);return cache.get(key);}public void put(int key, int value) {
if (cache.containsKey(key)) {
cache.put(key, value);makeKeyRecently(key);return;}if (cache.size() >= this.size) {
int oldestKey = cache.keySet().iterator().next();cache.remove(oldestKey);}cache.put(key, value);}private void makeKeyRecently(int key) {
int val = cache.get(key);cache.remove(key);cache.put(key, val);}}
}