LRU Cache_leetcode_go实现一个LRU缓存,c

2018-11-07  本文已影响0人  fjxCode

LRU Cache_leetcode_go实现一个LRU缓存,container/list.Remove()内存释放的坑,指针传递,container/list元素改值

题目:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

思路:

错解(存在无法更新值的问题):

type LRUCache struct {
    lru   *list.List
    store map[int]*list.Element
    cap   int
}

type LruKv struct {
    lruK int
    lruV int
}

func Constructor(capacity int) LRUCache {
    return LRUCache{
        lru:   list.New(),
        store: make(map[int]*list.Element, capacity),
        cap:   capacity,
    }
}

func (this *LRUCache) Get(key int) int {
    elem, ok := this.store[key]
    if !ok {
        return -1
    }

    //更新lru
    this.lru.Remove(elem) //map保存指针,方便删除
    node := elem.Value.(LruKv)
    this.lru.PushBack(LruKv{lruK: node.lruK, lruV: node.lruV,})
    
    return elem.Value.(LruKv).lruV
}

func (this *LRUCache) Put(key int, value int) {
    elem, ok := this.store[key]
    if ok {
        lruKvObj := elem.Value.(LruKv)
        lruKvObj.lruV = value //map的v存成指针,方便更新值
        this.lru.Remove(elem)
        this.lru.PushBack(elem.Value.(LruKv))
    } else {
        this.lru.PushBack(LruKv{lruK:key,lruV:value})
        lruKvObj := this.lru.Back()
        this.store[key] = lruKvObj
    }

    //处理cap
    if this.lru.Len() > this.cap {
        elem := this.lru.Front()
        node := elem.Value.(LruKv)
        delete(this.store, node.lruK)
        this.lru.Remove(elem)
    }
}

解决:要注意container/list中的elem.Value.(type)是值传递,而不是引用传递,无法改值。只重重建节点再插入。解决办法是改list.Element.Value的类型为*LruKv。

错解:(有一个关于container/list修改值的坑)

package main

import (
    "container/list"
)

type LRUCache struct {
    lru   *list.List
    store map[int]*list.Element
    cap   int
}

type LruKv struct {
    lruK int
    lruV int
}

func Constructor(capacity int) LRUCache {
    return LRUCache{
        lru:   list.New(),
        store: make(map[int]*list.Element, capacity),
        cap:   capacity,
    }
}

func (this *LRUCache) Get(key int) int {
    elem, ok := this.store[key]
    if !ok {
        return -1
    }

    //更新lru
    this.lru.Remove(elem) //map保存指针,方便删除
    node := elem.Value.(*LruKv)
    this.lru.PushBack(&LruKv{lruK: node.lruK, lruV: node.lruV,})

    return elem.Value.(*LruKv).lruV
}

func (this *LRUCache) Put(key int, value int) {
    elem, ok := this.store[key]
    if ok {
        lruKvObj := elem.Value.(*LruKv)
        lruKvObj.lruV = value //map的v存成指针,方便更新值
        this.lru.Remove(elem)
        this.lru.PushBack(lruKvObj)
    } else {
        this.lru.PushBack(&LruKv{lruK:key,lruV:value})
        lruKvObj := this.lru.Back()
        this.store[key] = lruKvObj
    }

    //处理cap
    if this.lru.Len() > this.cap {
        elem := this.lru.Front()
        node := elem.Value.(*LruKv)
        delete(this.store, node.lruK)
        this.lru.Remove(elem)
    }
}

问题分析:一个用container/list的坑,this.lru.Remove(e Element)。为避免内存泄露,释放了e的存储空间。实现为利用e的prev next指针进行删除。所以要求Element不仅要有Value,还要附带链表信息。
由于是引用传递,所以会清空map[]中的值。导致出现的问题是map[key]中的*Element仅有Value,没有链表信息。在插入重复元素时删除会失败。产生了冗余元素。

所以矛盾冲突在于list.Remove()方法的形参是引用传递,而本例实现map也是引用传递。在调用list.Remove()时,会析构形参*Element,影响其作为map的value被使用。影响的结果是清空了*Element所属的链表信息。进而导致更新value时,执行失败。元素个数多于预期。进而触发了扩容清理,从而导致逻辑错误。

解决:调用l.Remove()之后,更新map[]的对应值。

package main

import (
    "container/list"
    "fmt"
)

type LRUCache struct {
    lru   *list.List
    store map[int]*list.Element
    cap   int
}

type LruKv struct {
    lruK int
    lruV int
}

func Constructor(capacity int) LRUCache {
    return LRUCache{
        lru:   list.New(),
        store: make(map[int]*list.Element, capacity),
        cap:   capacity,
    }
}

func (this *LRUCache) Get(key int) int {
    elem, ok := this.store[key]
    if !ok {
        return -1
    }

    //更新lru
    this.lru.Remove(elem) //map保存指针,方便删除
    node := elem.Value.(*LruKv)
    this.lru.PushBack(&LruKv{lruK: node.lruK, lruV: node.lruV,})
    this.store[key] = this.lru.Back()

    return elem.Value.(*LruKv).lruV
}

func (this *LRUCache) Put(key int, value int) {
    elem, ok := this.store[key]
    if ok {
        lruKvObj := elem.Value.(*LruKv)
        lruKvObj.lruV = value //map的v存成指针,方便更新值
        this.lru.Remove(elem)
        this.lru.PushBack(lruKvObj)
        //特殊应对l.Remove()
        this.store[key] = this.lru.Back()
    } else {
        this.lru.PushBack(&LruKv{lruK:key,lruV:value})
        lruKvObj := this.lru.Back()
        this.store[key] = lruKvObj
    }

    //处理cap
    if this.lru.Len() > this.cap {
        elem := this.lru.Front()
        node := elem.Value.(*LruKv)
        delete(this.store, node.lruK)
        this.lru.Remove(elem)
    }
}

这个题测试输入太长,并且链表的变量跟踪进入的很深。调试了半天,所以mark一下Accepted。还有需要改进的地方。附注*Element存入map是指针,*Element.Value的值也是指针,才能实现改值。要不就要重新构建,并给map赋值。这也带了上述的问题。

Runtime: 176 ms, faster than 75.26% of Go online submissions for LRU Cache.

//TODO 需要做的优化,直接用双链表实现。container/list的Element很难用,编程变量都是一大串。还要做类型判断,简便地不要用.(type),直接用.(LruKv)一行代码返回对象。

上一篇下一篇

猜你喜欢

热点阅读