Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. class LRUCache {
  2.  
  3. let capacity: Int
  4.  
  5. var dict: [Int: Node] = [:]
  6. var cache = DoubleList()
  7.  
  8. init(_ capacity: Int) {
  9. self.capacity = capacity
  10. }
  11.  
  12. func get(_ key: Int) -> Int {
  13. guard let val = dict[key]?.val else {
  14. return -1
  15. }
  16. put(key, val)
  17. return val
  18. }
  19.  
  20. func put(_ key: Int, _ value: Int) {
  21. let new = Node(key: key, val: value)
  22. if let node = dict[key] {
  23. cache.delete(node: node)
  24. cache.insert(node: new)
  25. dict[key] = new
  26. } else {
  27. cache.insert(node: new)
  28. if cache.size > capacity {
  29. if let last = cache.deleteLast() {
  30. dict[last.key] = nil
  31. }
  32. }
  33. dict[key] = new
  34. }
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement