search——LRU

LRU (Least Recently Used) 最近最少使用算法
实现思路:k,v存储形式,数据结构为map+双向链表
map中key对应的value指向链表上的某个节点
插入新值时,将新值组装成节点放在链表头部,并将key加入map,value指向链表头部节点
当获取一个已经存在的值时,将存储该值的链表节点移到链表头部
当插入的值的数量达到预设的上限时,移除链表尾部的节点,移除map中对应的key

package main

import (
	"container/list"
	"fmt"
)

type LRUCache[K comparable, V any] struct {
	cap   int
	cache map[K]*list.Element
	list  *list.List
}
type entity[K comparable, V any] struct {
	key   K
	value V
}

func New[K comparable, V any](cap int) LRUCache[K, V] {
	return LRUCache[K, V]{
		cap:   cap,
		list:  list.New(),
		cache: make(map[K]*list.Element),
	}
}

func (l *LRUCache[K, V]) Get(key K) (V, bool) {
	if elem, ok := l.cache[key]; ok {
		l.list.MoveToFront(elem)
		return elem.Value.(entity[K, V]).value, true
	}
	return *new(V), false
}

func (l *LRUCache[K, V]) Set(key K, value V) {
	if elem, ok := l.cache[key]; ok {
		l.list.MoveToFront(elem)
		elem.Value = entity[K, V]{key, value}
	} else {
		if l.list.Len() >= l.cap {
			delete(l.cache, l.list.Back().Value.(entity[K, V]).key)
			l.list.Remove(l.list.Back())
		}
		l.list.PushFront(entity[K, V]{key, value})
		l.cache[key] = l.list.Front()
	}
}

func main() {
	l := New[string, int](3)
	l.Set("a", 1)
	l.Set("b", 2)
	l.Set("c", 3)
	l.Set("d", 4)
	fmt.Println(l.Get("c"))
	fmt.Println(l.Get("d"))
	fmt.Println(l.Get("b"))
	fmt.Println(l.Get("a"))
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

metabit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值