forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRUCache.swift
90 lines (69 loc) · 1.76 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
/**
* Question Link: https://leetcode.com/problems/lru-cache/
* Primary idea: Use linked list and hash map to build the cache.
* Time Complexity Per Action: O(1), Space Complexity: O(K)
*
*/
class LRUCache {
private let capacity: Int
private var count = 0
private let head = LRUCacheNode(0, 0)
private let tail = LRUCacheNode(0, 0)
private var dict = [Int: LRUCacheNode]()
init(_ capacity: Int) {
self.capacity = capacity
head.next = tail
tail.pre = head
}
func get(_ key: Int) -> Int {
if let node = dict[key] {
remove(key)
insert(node)
return node.val
}
return -1
}
func put(_ key: Int, _ value: Int) {
if let node = dict[key] {
node.val = value
remove(key)
insert(node)
return
}
let node = LRUCacheNode(key, value)
dict[key] = node
if count == capacity, let tailKey = tail.pre?.key {
remove(tailKey)
}
insert(node)
}
private func insert(_ node: LRUCacheNode) {
dict[node.key] = node
node.next = head.next
head.next?.pre = node
node.pre = head
head.next = node
count += 1
}
private func remove(_ key: Int) {
guard count > 0, let node = dict[key] else {
return
}
dict[key] = nil
node.pre?.next = node.next
node.next?.pre = node.pre
node.pre = nil
node.next = nil
count -= 1
}
}
fileprivate class LRUCacheNode {
let key: Int
var val: Int
var pre: LRUCacheNode?
var next: LRUCacheNode?
init(_ key: Int, _ val: Int) {
self.key = key
self.val = val
}
}