#### 题目

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

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.put(4, 4);    // evicts key 1
cache.get(3);       // returns 3
cache.get(4);       // returns 4

1. capacity: 最多保存的cache 数目, 如果多于的话则最旧的那条可以删除
2. get 的时候相当于一次refresh,这个key则会重新在cache list最新的位置

#### 思路

class Node {
var key: Int
var value: Int
var next: Node?
weak var prev: Node?

init(key: Int, value: Int) {
self.key = key
self.value = value
}
}

class LRUCache {
var capacity: Int
var dict: [Int: Node]
var tail: Node

init(_ capacity: Int) {
self.capacity = capacity
self.dict = [Int: Node]()
self.head = Node(key: 0, value: 0)
self.tail = Node(key: 0, value: 0)
}

func get(_ key: Int) -> Int {
if let node = dict[key] {
remove(node: node)
return node.value
} else {
return -1
}
}

func put(_ key: Int, _ value: Int) {
if let node = dict[key] {
remove(node: node)
}

let newNode = Node(key: key, value: value)
dict[key] = newNode

if dict.count > capacity {
remove(node: first)
dict.removeValue(forKey: first.key)
}
}

let last = self.tail.prev!
last.next = node
node.prev = last
node.next = tail
tail.prev = node
}

private func remove(node: Node) {
guard let prev = node.prev, let next = node.next else {
return
}

prev.next = next
next.prev = prev
}
}