-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsolution.go
80 lines (69 loc) · 1.44 KB
/
solution.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
package main
import (
"container/heap"
"fmt"
)
// Point in a coordinate system
type Point struct {
x int
y int
distance int
index int
}
// PriorityQueue contains points
type PriorityQueue []*Point
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
return pq[i].distance > pq[j].distance
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
// Push point into PriorityQueue
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
point := x.(*Point)
point.index = n
*pq = append(*pq, point)
}
// Pop point from PriorityQueue
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
point := old[n-1]
point.index = -1 // for safety
*pq = old[0 : n-1]
return point
}
func kClosest(points [][]int, K int) [][]int {
pq := make(PriorityQueue, len(points))
for i := range points {
pq[i] = &Point{
x: points[i][0],
y: points[i][1],
distance: (points[i][0]*points[i][0] + points[i][1]*points[i][1]) * -1,
index: i,
}
}
heap.Init(&pq)
var result [][]int
for K > 0 {
point := heap.Pop(&pq).(*Point)
result = append(result, []int{point.x, point.y})
K--
}
return result
}
func main() {
points := [][]int{
{3, 3},
{5, -1},
{-2, 4},
}
fmt.Printf("%#v", kClosest(points, 2))
}