MCPcopy
hub / github.com/austingebauer/go-leetcode / Put

Method Put

lru_cache_146/solution.go:28–69  ·  view source on GitHub ↗
(key int, value int)

Source from the content-addressed store, hash-verified

26}
27
28func (cache *LRUCache) Put(key int, value int) {
29 existingNode, ok := cache.keyMap[key]
30 if ok {
31 existingNode.value = value
32 cache.bringNodeToFront(existingNode)
33 return
34 }
35
36 node := &LRUNode{
37 key: key,
38 value: value,
39 }
40 cache.keyMap[key] = node
41
42 // no need to evict, so place in front of list
43 if cache.load < cache.capacity {
44 if cache.front == nil && cache.rear == nil {
45 cache.front = node
46 cache.rear = node
47 } else {
48 cache.insertInFront(node)
49 }
50
51 cache.load = cache.load + 1
52 return
53 }
54
55 // load is equal to capacity, so need to evict the LRU
56 evicted := cache.keyMap[cache.rear.key]
57 delete(cache.keyMap, cache.rear.key)
58
59 // a single node is to be evicted
60 if evicted.next == nil && evicted.prev == nil {
61 cache.front = node
62 cache.rear = node
63 return
64 }
65
66 cache.rear = cache.rear.prev
67 cache.rear.next = nil
68 cache.insertInFront(node)
69}
70
71func (cache *LRUCache) Get(key int) int {
72 node, ok := cache.keyMap[key]

Callers 8

TestLRUCache_1Function · 0.80
TestLRUCache_2Function · 0.80
TestLRUCache_3Function · 0.80
TestLRUCache_4Function · 0.80
TestLRUCache_5Function · 0.80
TestLRUCache_6Function · 0.80
TestLRUCache_7Function · 0.80
TestLRUCache_8Function · 0.80

Calls 2

bringNodeToFrontMethod · 0.95
insertInFrontMethod · 0.95

Tested by 8

TestLRUCache_1Function · 0.64
TestLRUCache_2Function · 0.64
TestLRUCache_3Function · 0.64
TestLRUCache_4Function · 0.64
TestLRUCache_5Function · 0.64
TestLRUCache_6Function · 0.64
TestLRUCache_7Function · 0.64
TestLRUCache_8Function · 0.64