首页 > 代码库 > 146. LRU Cache
146. LRU Cache
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.
难一点的设计的题一般就是double list + hashmap<key, node>[LRU , mid stack] or tree + hashmap <key, node> [relation tree or tire]
//new node in the tail, old node in the head; class DoubleList{ int key; int val; DoubleList prev; DoubleList next; public DoubleList(int key, int val){ this.key = key; this.val = val; } } public class LRUCache { int index = 0; int capacity; DoubleList tail; DoubleList head; HashMap<Integer, DoubleList> map; public LRUCache(int capacity) { this.capacity = capacity; this.map = new HashMap<Integer, DoubleList>(); this.head = new DoubleList(0,0); this.tail = new DoubleList(0,0); head.next = tail; tail.prev = head; this.index = 0; } public void addFirst(DoubleList node){ node.next= head.next; node.next.prev = node; node.prev = head; head.next = node; } public void remove(DoubleList node){ node.prev.next = node.next; node.next.prev = node.prev; } public int get(int key) { if(map.containsKey(key)){ DoubleList node = map.get(key); remove(node); addFirst(node); return node.val; } return -1; } public void set(int key, int value) { if(map.containsKey(key)){ map.get(key).val = value; DoubleList node = map.get(key); remove(node); addFirst(node); return; } else{ DoubleList node = new DoubleList(key, value); map.put(key, node); if(index < capacity){ index ++; addFirst(node); } else{ map.remove(tail.prev.key); remove(tail.prev); addFirst(node); } } } }
146. LRU Cache
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。