Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

146. LRU 缓存机制 #86

Open
Geekhyt opened this issue Sep 20, 2021 · 0 comments
Open

146. LRU 缓存机制 #86

Geekhyt opened this issue Sep 20, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 20, 2021

原题链接

借用 Map

Map 的键值是有序的,可以按照插入的顺序返回键值。

  1. 元素存在就将其更新
  2. this.cache.keys().next().value: 获取到头部元素(也就是最远使用的元素)的 key
const LRUCache = function(capacity) {
    this.cap = capacity
    this.cache = new Map()
}

LRUCache.prototype.get = function(key) {
    if (this.cache.has(key)) {
        let temp = this.cache.get(key)
        this.cache.delete(key)
        this.cache.set(key, temp)
        return temp
    } else {
        return -1
    }
}

LRUCache.prototype.put = function(key, value) {
    if (this.cache.has(key)) {
        this.cache.delete(key)
    } else if (this.cache.size === this.cap) {
        this.cache.delete(this.cache.keys().next().value)
    }
    this.cache.set(key,value)
}
  • 时间复杂度:O(1)
  • 空间复杂度:O(n)
@Geekhyt Geekhyt added the 中等 label Sep 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant