Skip to content

Commit

Permalink
Merge pull request #77 from arunsathiya/solve/146-lru-cache
Browse files Browse the repository at this point in the history
146. Lru Cache
  • Loading branch information
arunsathiya committed Feb 27, 2024
2 parents 20efb94 + 635d898 commit 188be33
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/146-lru-cache/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import "container/list"

type LRUCache struct {
capacity int
cache map[int]*list.Element
list *list.List
}

type pair struct {
key, value int
}

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

func (this *LRUCache) Get(key int) int {
if element, found := this.cache[key]; found {
this.list.MoveToFront(element)
return element.Value.(pair).value
}
return -1
}

func (this *LRUCache) Put(key int, value int) {
if element, found := this.cache[key]; found {
this.list.MoveToFront(element)
element.Value = pair{key, value}
} else {
if this.list.Len() == this.capacity {
oldest := this.list.Back()
delete(this.cache, oldest.Value.(pair).key)
this.list.Remove(oldest)
}
this.cache[key] = this.list.PushFront(pair{key, value})
}
}

0 comments on commit 188be33

Please sign in to comment.