问题描述:
解题思路:
采用哈希表+双向链表较为方便时间。双向链表便于维护数据最近使用再前,最久未使用在后。双向链表便于移动删除。
题解:
class LRUCache { class DlinkedNode{ int key; int value; DlinkedNode prev; DlinkedNode next; public DlinkedNode(){}; public DlinkedNode(int _key,int _value){key = _key;value = _value;}; } private Mapcache = new HashMap (); private int size; private int capacity; private DlinkedNode head; private DlinkedNode tail; public LRUCache(int capacity) { this.capacity = capacity; this.size = 0; head = new DlinkedNode(); tail = new DlinkedNode(); head.next = tail; tail.prev = head; } public int get(int key) { DlinkedNode node = cache.get(key); if(node == null){ return -1; } moveToHead(node); return node.value; } public void put(int key, int value) { DlinkedNode node = cache.get(key); if(node == null){ DlinkedNode node1 = new DlinkedNode(key,value); cache.put(key,node1); addToHead(node1); size++; if(size>capacity){ DlinkedNode node2 = removeToTail(); cache.remove(node2.key); size--; } }else{ node.value = value; moveToHead(node); } } private void addToHead(DlinkedNode node){ node.prev = head; node.next = head.next; head.next.prev = node; head.next = node; } private void removeNode(DlinkedNode node){ node.prev.next = node.next; node.next.prev = node.prev; } private void moveToHead(DlinkedNode node){ removeNode(node); addToHead(node); } private DlinkedNode removeToTail(){ DlinkedNode node = tail.prev; removeNode(node); return node; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)