Skip to content

Commit 59a39a8

Browse files
authored
Create Solution2.go
1 parent c94329e commit 59a39a8

File tree

1 file changed

+31
-0
lines changed
  • solution/0900-0999/0973.K Closest Points to Origin

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
func kClosest(points [][]int, k int) [][]int {
2+
maxQ := hp{}
3+
for i, p := range points {
4+
dist := math.Hypot(float64(p[0]), float64(p[1]))
5+
heap.Push(&maxQ, pair{dist, i})
6+
if len(maxQ) > k {
7+
heap.Pop(&maxQ)
8+
}
9+
}
10+
ans := make([][]int, k)
11+
for i, p := range maxQ {
12+
ans[i] = points[p.i]
13+
}
14+
return ans
15+
}
16+
17+
type pair struct {
18+
dist float64
19+
i int
20+
}
21+
22+
type hp []pair
23+
24+
func (h hp) Len() int { return len(h) }
25+
func (h hp) Less(i, j int) bool {
26+
a, b := h[i], h[j]
27+
return a.dist > b.dist
28+
}
29+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
30+
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
31+
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }

0 commit comments

Comments
 (0)