LeetCode LRU Cache

来源:互联网 发布:mac cs6破解方法 编辑:程序博客网 时间:2024/05/01 04:31

LRU Cache

 Total Accepted: 18145 Total Submissions: 129196My Submissions

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Submission Result: Accepted
这个题的思路很简单,就是用一个MAP去管理Node,通过Hash做到O(1)的操作,但是写起来容易出BUG。
public class LRUCache {int capacity;DoubleLinkedList head = null;DoubleLinkedList end = null;HashMap<Integer,DoubleLinkedList> map = new HashMap<Integer,DoubleLinkedList>();public LRUCache(int capacity) {this.capacity = capacity;}public int get(int key) {if(map.containsKey(key)){DoubleLinkedList cur = map.get(key);delete(cur);toHead(cur);return cur.val;}return -1;}public void delete(DoubleLinkedList node) {DoubleLinkedList cur = node;DoubleLinkedList pre = cur.pre;DoubleLinkedList post = cur.next; if (pre != null) {pre.next = post;} else {head = post;} if (post != null) {post.pre = pre;} else {end = pre;}}public void toHead(DoubleLinkedList node){if(head != null){node.next = head;head.pre = node;node.pre = null;head = node;}else{head = node;if(end == null){end = node;    }}}public void set(int key, int value) {if(!map.containsKey(key)){DoubleLinkedList newNode = new DoubleLinkedList(key, value);if(head == null){head = newNode;end =  newNode;}map.put(key,newNode);if(map.size() > capacity){int removKey = end.key;        map.remove(removKey);if (end != null) {end.next = null;}        toHead(newNode);}else{toHead(newNode);}}else{DoubleLinkedList curNode = map.get(key);curNode.val = value;if(curNode != head){delete(curNode);toHead(curNode);    }}}}class DoubleLinkedList{int key;int val;DoubleLinkedList pre = null;DoubleLinkedList next = null;DoubleLinkedList(int key, int val){this.key = key;this.val = val;}}


0 0