吹拉弹唱


  • Home
  • Archive
  • Categories
  • Tags
  • Books
  •  

© 2022 Kleon

Theme Typography by Makito

Proudly published with Hexo

Code - Heap

Posted at 2022-05-05Updated at 2022-05-05 interview  interview algorithm 

  • LeetCode
    • 460. LFU Cache

# LeetCode

# 460. LFU Cache

leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
type Node struct {
key int
value int
freq int
index int
pos int
}

func NewNode(key, value, index int) *Node{
return &Node{key, value, 1, index, 0}
}

type NodeHeap []*Node

func (h NodeHeap) Len() int { return len(h) }

func (h NodeHeap) Less(i, j int) bool {
if h[i].freq == h[j].freq {
return h[i].index < h[j].index
}
return h[i].freq < h[j].freq
}

func (h NodeHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].pos = i
h[j].pos = j
}

func (h *NodeHeap) Push(x interface{}) {
n := len(*h)
node := x.(*Node)
node.pos = n
*h = append(*h, node)
}

func (h *NodeHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
old[n-1] = nil // avoid mem leak
x.pos = -1
*h = old[:n-1]
return x
}

type LFUCache struct {
capacity int
pq *NodeHeap
cache map[int]*Node
size int
index int
}


func Constructor(capacity int) LFUCache {
return LFUCache{
pq: &NodeHeap{},
cache: map[int]*Node{},
index: 1,
capacity: capacity,
}
}

func (this *LFUCache) Get(key int) int {
node, exists := this.cache[key]
if !exists {
return -1
}
node.freq++
node.index = this.index
this.index++
heap.Fix(this.pq, node.pos)
// for i := range *this.pq {
// fmt.Printf("%v|%v|%v,", (*this.pq)[i].key, (*this.pq)[i].freq, (*this.pq)[i].index)
// }
// fmt.Printf("\n")
return node.value
}

func (this *LFUCache) Put(key int, value int) {
if this.capacity == 0 {
return
}
node, exists := this.cache[key]
if exists {
node.value = value
node.freq++
node.index = this.index
this.index++
heap.Fix(this.pq, node.pos)
} else {
if this.size == this.capacity {
node := heap.Pop(this.pq).(*Node)
// fmt.Printf("delete %v\n", node.key)
delete(this.cache, node.key)
this.size--
}
node := NewNode(key, value, this.index)
this.index++
heap.Push(this.pq, node)
this.cache[key] = node
this.size++
}
// for i := range *this.pq {
// fmt.Printf("%v|%v|%v,", (*this.pq)[i].key, (*this.pq)[i].freq, (*this.pq)[i].index)
// }
// fmt.Printf("\n")
}


/**
* Your LFUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/

Share 

 Previous post: Code - Hash Table Next post: Code - Linked List 

© 2022 Kleon

Theme Typography by Makito

Proudly published with Hexo