forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRUCache.swift
91 lines (68 loc) · 1.89 KB
/
LRUCache.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Question Link: https://leetcode.com/problems/lru-cache/
* Primary idea: Use Doubly linked list and hash table to build the LRU cache.
* Time Complexity: O(1), Space Complexity: O(n)
*
*/
class LRUCache {
private let capacity: Int
private let head = Node(0, 0)
private let tail = Node(0, 0)
private var keyNodeMap = [Int: Node]()
init(_ capacity: Int) {
self.capacity = capacity
head.next = tail
tail.prev = head
}
func get(_ key: Int) -> Int {
guard let node = keyNodeMap[key] else {
return -1
}
remove(node)
moveToHead(node)
return node.val
}
func put(_ key: Int, _ value: Int) {
let node = Node(key, value)
if let lastNode = keyNodeMap[key] {
remove(lastNode)
}
keyNodeMap[key] = node
moveToHead(node)
if keyNodeMap.count > capacity {
keyNodeMap[tail.prev!.key] = nil
remove(tail.prev!)
}
}
private func remove(_ node: Node) {
let prev = node.prev
let post = node.next
prev!.next = post
post!.prev = prev
node.next = nil
node.prev = nil
}
private func moveToHead(_ node: Node) {
let first = head.next
head.next = node
node.prev = head
node.next = first
first!.prev = node
}
class Node {
let key: Int
var val: Int
var prev: Node?
var next: Node?
init(_ key: Int, _ val: Int) {
self.key = key
self.val = val
}
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* let obj = LRUCache(capacity)
* let ret_1: Int = obj.get(key)
* obj.put(key, value)
*/