Skip to content

Instantly share code, notes, and snippets.

@haoyu-c
Created September 25, 2019 15:07
Show Gist options
  • Save haoyu-c/6aa450e907d6b937965e2d4350529f02 to your computer and use it in GitHub Desktop.
Save haoyu-c/6aa450e907d6b937965e2d4350529f02 to your computer and use it in GitHub Desktop.
class LRUCache {
let capacity: Int
var dict: [Int: Node] = [:]
var cache = DoubleList()
init(_ capacity: Int) {
self.capacity = capacity
}
func get(_ key: Int) -> Int {
guard let val = dict[key]?.val else {
return -1
}
put(key, val)
return val
}
func put(_ key: Int, _ value: Int) {
let new = Node(key: key, val: value)
if let node = dict[key] {
cache.delete(node: node)
cache.insert(node: new)
dict[key] = new
} else {
cache.insert(node: new)
if cache.size > capacity {
if let last = cache.deleteLast() {
dict[last.key] = nil
}
}
dict[key] = new
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment