-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (68 loc) · 1.18 KB
/
main.go
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
package main
import (
"container/heap"
"fmt"
"math"
)
func main() {
fmt.Println("Hello world")
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func closestKValues(root *TreeNode, target float64, k int) []int {
pq := &PQ{}
heap.Init(pq)
var runner func(node *TreeNode)
runner = func(node *TreeNode) {
if node == nil {
return
}
heap.Push(pq, info{getDist(target, node.Val), node.Val})
if pq.Len() > k {
heap.Pop(pq)
}
runner(node.Left)
runner(node.Right)
}
runner(root)
var result []int
for pq.Len() > 0 {
i := pq.Pop().(info)
result = append(result, i.val)
}
return result
}
func getDist(orig float64, x int) float64 {
return abs(orig - float64(x))
}
func abs(a float64) float64 {
return math.Abs(a)
}
type info struct {
dist float64
val int
}
type PQ []info
func (pq PQ) Len() int {
return len(pq)
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
// max-heap
func (pq PQ) Less(i, j int) bool {
return pq[i].dist > pq[j].dist
}
func (pq *PQ) Push(x interface{}) {
tmp := x.(info)
*pq = append(*pq, tmp)
}
func (pq *PQ) Pop() interface{} {
n := len(*pq)
tmp := (*pq)[n-1]
*pq = (*pq)[:n-1]
return tmp
}