File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
solution/0900-0999/0973.K Closest Points to Origin Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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 }
You can’t perform that action at this time.
0 commit comments