当前位置: 首页 > article >正文

《零基础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


http://www.kler.cn/a/504577.html

相关文章:

  • rtthread学习笔记系列--28 I2C驱动
  • 【C语言】【C++】Curl库的安装
  • 基于Python机器学习、深度学习技术提升气象、海洋、水文领域实践应用-以ENSO预测为例讲解
  • 机组存储系统
  • HarmonyOS NEXT开发进阶(六):HarmonyOS NEXT实现嵌套 H5 及双向通信
  • 【跟着官网学技术系列之MySQL】第6天之输入查询
  • 改进萤火虫算法之八:量子萤火虫算法(Quantum-behaved Firfly Algorithm,QFA)
  • 开疆智能Profient转DeviceNET主网关连接发那科机器人配置案例
  • excel 整理表格,分割一列变成多列数据
  • Mac远程控制电脑Windows怎么弄?
  • 走出实验室的人形机器人,将复刻ChatGPT之路?
  • centos 7 Samba服务器的配置
  • 【BLE】CC2541之使用自定义128bit的UUID
  • uniapp 绘制五星评分 精确到半星
  • Linux C 使用ZBar库解析二维码和条形码
  • 数据结构——线性表和顺序表
  • 在 Debian 上安装 Docker
  • UML系列之Rational Rose笔记九:组件图
  • intel x99主板设置上电服务器自动启动
  • 机器学习之DBSCAN算法自动分类