LRU问题 Go版本

题目描述

设计LRU缓存结构,该结构在构造时确定大小,假设大小为K,并有如下两个功能
  • set(key, value):将记录(key, value)插入该结构
  • get(key):返回key对应的value值
[要求]
  1. set和get方法的时间复杂度为O(1)
  2. 某个key的set或get操作一旦发生,认为这个key的记录成了最常使用的。
  3. 当缓存的大小超过K时,移除最不经常使用的记录,即set或get最久远的。
若opt=1,接下来两个整数x, y,表示set(x, y)
若opt=2,接下来一个整数x,表示get(x),若x未出现过或已被移除,则返回-1
对于每个操作2,输出一个答案

版本一、

func LRU( operators [][]int ,  k int ) []int {
    // write code here
    res := make([]int,0,len(operators))
    key := make([]int,k)
    val := make([]int,k)
    for _,va := range operators{
        switch{
            case va[0] == 1:
            if len(key)==k{
                key = key[1:]
                val = val[1:]
            }
            key = append(key, va[1])
            val = append(val, va[2])
            break
            case va[0] == 2 :
            idx := -1
            for i:=0;i<len(key);i++{
                    if key[i] == va[1]{
                        idx = i
                        break
                    }
                }
                if idx == -1{
                    res = append(res, -1)
                }else{
                    res = append(res, val[idx])
                    if idx<k-1{
                        key = append(key[:idx], append(key[idx+1:],key[idx])...)
                        val = append(val[:idx], append(val[idx+1:],val[idx])...)
                    }
                }
             
            break
        }
         
    }
    return res
}

版本二、

package main
 
/**
 * lru design
 * @param operators int整型二维数组 the ops
 * @param k int整型 the k
 * @return int整型一维数组
*/
type ListNode struct{
  	Key int
	Val int
  	Pre *ListNode
  	Next *ListNode
}
type LRUCache struct{
	Val int
  	Ma map[int]*ListNode
  	Head *ListNode
  	Tail *ListNode
}
func Constructor(capacity int) LRUCache {
  h := ListNode{-1,0,nil,nil}
  t := ListNode{-1,0,nil,nil}
  h.Next = &t
  t.Pre = &h
  lru := LRUCache{Val:capacity,Map:make(map[int]*ListNode, capacity), Head:&h, Tail:&t}
  return lru
}

func (this *LRUCache) push_front(cur *ListNode){
  preHead := this.Head.Next
  cur.Next = preHead
  cur.Pre = this.Head
  preHead.Pre = cur
  this.Head.Next = cur
}

func (this *LRUCache)erase(cur *ListNode){
  pre,next := cur.Pre, cur.Next
  pre.Next, next.Pre = next, pre
}


func (this *LRUCache) Get(key int) int {
  cur,exist := this.Ma[key]
  if exist{
    this.erase(cur)
    this.push_front(cur)
    return cur.Val
  }else{
  	return -1
  }
}

func (this *LRUCache) Set(key int, val int){
  cur, exist := this.Map[key]
  if exist{
  	cur.Val = val
    this.erase(cur)
    this.push_front(cur)
  }else{
    if len(this.Ma) == this.Val{
      tail := this.Tail.Pre
      this.erase(tail)
      delete(this.Map, tail.Key)
    }
    newNode := ListNode{Key:key,Val:val,Pre:nil,Next:nil}
    this.Ma[key] = &newNode
    this.push_front(&newNode)
  }
}

  

posted @ 2021-02-25 22:58  布尔先生  阅读(108)  评论(0编辑  收藏  举报