最近在學習算法的視頻和題目,提高一下自己的算法方面的能力。
分享一個關於 LRU (最近最少使用) 緩存機制 的題 鏈接在此 https://leetcode-cn.com/problems/lru-cache/
下面是我用java實現的一個實例 親測可用 ,可能會有bug
package com.haozhen.lru; /** * author haozhen * email [email protected] */ public class LRUCache { public static void main(String[] args) { LRUCache cache = new LRUCache( 2 /* 緩存容量 */ ); cache.put(1, 1); cache.put(2, 2); System.out.println(cache.get(1)); // 返回 1 cache.put(3, 3); // 該操作會使得關鍵字 2 作廢 System.out.println(cache.get(2)); // 返回 -1 (未找到) cache.put(4, 4); // 該操作會使得關鍵字 1 作廢 System.out.println(cache.get(1)); // 返回 -1 (未找到) System.out.println(cache.get(3)); // 返回 3 System.out.println(cache.get(4)); // 返回 4 } private Node head = null; private Node tail = head; private int size; private int capacity; class Node{ private Node pre; private Node next; private int key; private int value; public void setPre(Node pre){ this.pre = pre; } public Node getPre(){ return this.pre; } public void setNext(Node next){ this.next = next; } public Node getNext(){ return this.next; } public Node(int key,int value){ this.key = key; this.value = value; } public int getKey(){ return this.key; } public int getValue(){ return this.value; } } public LRUCache(int capacity) { if(capacity<1){ throw new RuntimeException("capacity 必須大於0"); } this.capacity = capacity; } public int get(int key) { Node n = this.getNodeByKey(key); if(n!=null){ setHeadNode(n); return n.getValue(); } return -1; } public Node getNodeByKey(int key){ Node n = this.head; while(n!=null){ if(n.getKey()==(key)){ return n; } n = n.getNext(); } return null; } public void setHeadNode(Node n2){ Node pre = n2.getPre(); if(pre==null){ return; } Node next = n2.getNext(); if(next==null){ pre.setNext(null); }else{ next.setPre(pre); pre.setNext(next); } this.tail = n2.getPre(); Node head = this.head; head.setPre(n2); n2.setNext(head); n2.setPre(null); this.head = n2; } public void put(int key, int value) { if(this.head==null){ Node n = new Node(key,value); this.head = n; this.tail = n; this.size = 1; }else{ if(this.size==this.capacity){ Node n2 = getNodeByKey(key); if(n2==null){//如果沒有這個key 就會添加這個key Node n = new Node(key,value); //將尾節點去掉 Node pre = this.tail.getPre(); pre.setNext(null); this.tail = pre; //將該節點置爲頭節點 Node head = this.head; head.setPre(n); n.setNext(head); this.head = n; }else{//將n2置爲頭節點 setHeadNode(n2); } }else{ Node n = new Node(key,value); Node head = this.head; n.setNext(head); head.setPre(n); this.head = n; this.size++; } } } }