《零基础Go语言算法实战》【题目 4-8】用 Go 语言设计一个遵循最近最少使用(LRU)缓存约束的数据结构

《零基础Go语言算法实战》

【题目 4-8】用 Go 语言设计一个遵循最近最少使用(LRU)缓存约束的数据结构

实现 LRUCache 类。

● LRUCache(int capacity) :初始化具有正大小容量的 LRU 缓存。

● int get(int key) :如果 key 存在,则返回 key 的值;否则返回 -1。

● void put(int key, int value) :如果键存在,则更新键的值;否则将键值对添加到缓存中。

如果密钥数量超过此操作的容量,则移除 LRU 的密钥。

● get() 和 put() 方法必须分别以 O(1) 的平均时间复杂度运行。

101

零基础

Go语言算法实战

【解答】

① 思路。

根据要求,可以通过双向链表来设计 LRUCache 对象及其 get()、put() 方法。

② Go 语言实现。

package main

import "fmt"

type LRUCache struct {

capacity int

head, tail *Node

values map[int]*Node

}

type Node struct {

key, value int

prev, next *Node

}

func Constructor(capacity int) LRUCache {

return LRUCache{

values: map[int]*Node{},

capacity: capacity,

}

}

func (lr *LRUCache) Get(key int) int {

node, ok := lr.values[key]

if !ok {

return -1

}

lr.moveToLast(node)

return node.value

}

func (lr *LRUCache) moveToLast(node *Node) {

if node == lr.tail {

return

}

if node == lr.head {

lr.head = lr.head.next

lr.head.prev = nil

} else {

node.prev.next = node.next

node.next.prev = node.prev

}

lr.tail.next = node

node.prev = lr.tail

lr.tail = lr.tail.next

lr.tail.next = nil

}

func (lr *LRUCache) Put(key int, value int) {

if _, ok := lr.values[key]; ok {

lr.values[key].value = value

lr.moveToLast(lr.values[key])

return

}

if len(lr.values) < lr.capacity {

lr.append(key, value)

return

}

node := lr.head

lr.moveToLast(node)

delete(lr.values, node.key)

lr.values[key] = node

node.key = key

node.value = value

}

func (lr *LRUCache) append(key, value int) {

node := &Node{

key: key,

value: value,

}

if lr.tail == nil {

lr.tail = node

lr.head = node

} else {

lr.tail.next = node

node.prev = lr.tail

lr.tail = node

}

lr.values[key] = node

}

func main() {

obj := Constructor(2)

obj.Put(5, 88)

res := obj.Get(5)

fmt.Println(res)

}

//$ go run interview4-8.go

//88

相关推荐
山烛11 分钟前
KNN 算法中的各种距离:从原理到应用
人工智能·python·算法·机器学习·knn·k近邻算法·距离公式
guozhetao24 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
吃着火锅x唱着歌27 分钟前
LeetCode 611.有效三角形的个数
算法·leetcode·职场和发展
CHANG_THE_WORLD3 小时前
金字塔降低采样
算法·金字塔采样
不知天地为何吴女士5 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界5 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
励志要当大牛的小白菜8 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970448 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵9 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
舒一笑9 小时前
我的开源项目-PandaCoder迎来史诗级大更新啦
后端·程序员·intellij idea