Leetcode- LRUCache
关键是搞懂题目(不知道LRUCache的只能自己google了)。
然后用双向链表来模拟cache被get和set。但是naive implementation会exceed time limit。所以最大的关键是用一个HashMap来记录key在链表中的位置,这样子每次查询是O(1)的时间,否则O(n)。
这个也是很经典的用Map来加速双向链表查询的思路(前提是key要唯一)。
import java.util.*; public class LRUCache { Map<Integer, DoubleLinkedListNode> hmap = new HashMap<Integer, DoubleLinkedListNode>(); DoubleLinkedListNode head = null; DoubleLinkedListNode tail = null; int capa; public LRUCache(int capacity) { this.capa = capacity; } public int get(int key) { if (hmap.containsKey(key)) { DoubleLinkedListNode tnode = hmap.get(key); tnode = removeNode(tnode); pushFront(tnode); return tnode.value; } return -1; } public void set(int key, int value) { if (hmap.containsKey(key) == true) { DoubleLinkedListNode tnode = hmap.get(key); tnode.value = value; tnode = removeNode(tnode); pushFront(tnode); } else { DoubleLinkedListNode newNode = new DoubleLinkedListNode(key,value); if (hmap.size() == capa) { hmap.remove(tail.key); removeNode(tail); } pushFront(newNode); hmap.put(key, newNode); } } void pushFront(DoubleLinkedListNode node) { if (head == null) { head = tail = node; } else { node.next = head; head.prev = node; head = node; } return; } DoubleLinkedListNode removeNode(DoubleLinkedListNode node) { DoubleLinkedListNode prev = node.prev; DoubleLinkedListNode next = node.next; if (prev != null) { prev.next = next; } else { head = next; } if (next != null) { next.prev = prev; } else { tail = prev; } node.prev = null; node.next = null; return node; } class DoubleLinkedListNode { int key; int value; DoubleLinkedListNode prev; DoubleLinkedListNode next; public DoubleLinkedListNode(int key, int val) { this.key = key; this.value = val; prev = null; next = null; } public DoubleLinkedListNode() { value = 0; prev = null; next = null; } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。