Created
September 25, 2019 15:07
-
-
Save haoyu-c/6aa450e907d6b937965e2d4350529f02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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