-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #77 from arunsathiya/solve/146-lru-cache
146. Lru Cache
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}) | ||
} | ||
} |