Skip to content

Commit 2db8a18

Browse files
committed
Add problem 973 - K Closest Points To Origin
1 parent 302f49c commit 2db8a18

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package heaps
2+
3+
import (
4+
"container/heap"
5+
6+
"github.com/anirudhology/leetcode-go/problems/util"
7+
)
8+
9+
func KClosestPointsToOrigin(points [][]int, k int) [][]int {
10+
// List to store k closest points
11+
var kClosestPoints [][]int
12+
// Special case
13+
if len(points) == 0 {
14+
return kClosestPoints
15+
}
16+
minHeap := &util.MinHeapPoint{}
17+
heap.Init(minHeap)
18+
for i, point := range points {
19+
distance := point[0]*point[0] + point[1]*point[1]
20+
heap.Push(minHeap, util.Point{Distance: distance, Index: i})
21+
}
22+
result := make([][]int, k)
23+
for i := 0; i < k; i++ {
24+
point := heap.Pop(minHeap).(util.Point)
25+
result[i] = points[point.Index]
26+
}
27+
return result
28+
}

problems/util/min_heap_point.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package util
2+
3+
type Point struct {
4+
Distance int
5+
Index int
6+
}
7+
8+
type MinHeapPoint []Point
9+
10+
func (h MinHeapPoint) Len() int { return len(h) }
11+
func (h MinHeapPoint) Less(i, j int) bool { return h[i].Distance < h[j].Distance }
12+
func (h MinHeapPoint) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
13+
14+
func (h *MinHeapPoint) Push(x interface{}) {
15+
*h = append(*h, x.(Point))
16+
}
17+
18+
func (h *MinHeapPoint) Pop() interface{} {
19+
old := *h
20+
n := len(old)
21+
x := old[n-1]
22+
*h = old[0 : n-1]
23+
return x
24+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package heaps_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/anirudhology/leetcode-go/problems/heaps"
7+
)
8+
9+
func TestKClosest(t *testing.T) {
10+
if res := heaps.KClosestPointsToOrigin([][]int{{1, 3}, {-2, 2}}, 1); len(res) != 1 || res[0][0] != -2 || res[0][1] != 2 {
11+
t.Errorf("expected [[-2, 2]], got %v", res)
12+
}
13+
if res := heaps.KClosestPointsToOrigin([][]int{{3, 3}, {5, -1}, {-2, 4}}, 2); len(res) != 2 || res[0][0] != 3 || res[0][1] != 3 || res[1][0] != -2 || res[1][1] != 4 {
14+
t.Errorf("expected [[3, 3], [-2, 4]], got %v", res)
15+
}
16+
if res := heaps.KClosestPointsToOrigin([][]int{{0, 1}, {1, 0}}, 1); len(res) != 1 || res[0][0] != 0 || res[0][1] != 1 {
17+
t.Errorf("expected [[0, 1]], got %v", res)
18+
}
19+
if res := heaps.KClosestPointsToOrigin([][]int{{1, 1}}, 1); len(res) != 1 || res[0][0] != 1 || res[0][1] != 1 {
20+
t.Errorf("expected [[1, 1]], got %v", res)
21+
}
22+
if res := heaps.KClosestPointsToOrigin([][]int{}, 0); len(res) != 0 {
23+
t.Errorf("expected [], got %v", res)
24+
}
25+
}

0 commit comments

Comments
 (0)