Swift 实现 LRU (最近最少使用) 缓存机制

https://leetcode-cn.com/problems/lru-cache/

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
以下是根据 Leetcode 上的代码泛型化后的实用代码.

class DoublyLinkedList{
    var key: K
    var value: V
    var previous: DoublyLinkedList?
    var next: DoublyLinkedList?
    
    init(_ key: K, _ value: V) {
        self.key = key
        self.value = value
    }
}

class LRUCache {
    var maxCapacity: Int
    var head: DoublyLinkedList
    var tail: DoublyLinkedList
    var cache: [K: DoublyLinkedList]
    
    init(key: K, value: V, maxCapacity: Int) {
        self.maxCapacity = maxCapacity
        self.cache = [K: DoublyLinkedList]()
        self.head = DoublyLinkedList(key, value)
        self.tail = DoublyLinkedList(key, value)
        self.head.next = self.tail
        self.tail.previous = self.head
    }
    
    func add(_ node: DoublyLinkedList){
        let next = head.next
        head.next = node
        node.previous = head
        node.next = next
        next?.previous = node
    }
    
    func removeAll() {
        self.head.next = self.tail
        self.tail.previous = self.head
        cache.removeAll()
    }
    
    func remove(_ key: K) {
        if let node = cache[key] {
            remove(node)
            cache.removeValue(forKey: key)
        }
    }
    
    func remove(_ node: DoublyLinkedList){
        let previous = node.previous
        let next = node.next
        previous?.next = next
        next?.previous = previous
    }
    
    func get(_ key: K) -> V?{
        if let node = cache[key]{
            remove(node)
            add(node)
            return node.value
        }
        return nil
    }
    
    func put(_ key: K, _ value: V){
        if let node = cache[key]{
            remove(node)
            cache.removeValue(forKey: key)
        }else if cache.keys.count >= maxCapacity{
            if let leastNode = tail.previous{
                remove(leastNode)
                cache.removeValue(forKey: leastNode.key)
            }
        }
        let newNode = DoublyLinkedList(key, value)
        cache[key] = newNode
        add(newNode)
    }
    
    subscript(index: K) -> V? {
        get {
            return get(index)
        }
        
        set {
            guard let newValue = newValue else {
                return
            }
            put(index, newValue)
        }
    }
}

使用方式,头尾的初始值这里有更好的解决方式希望可以告诉我.
private var cache = LRUCache(key: "", value: "", maxCapacity: 10)

理想的实用方式是这样
private var cache = LRUCache(maxCapacity: 10)

你可能感兴趣的:(Swift 实现 LRU (最近最少使用) 缓存机制)