Skip to content

Commit bed3599

Browse files
committed
Add: K Closest Points to Origin
1 parent 837375f commit bed3599

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package k_closest_points_to_origin
2+
3+
import "sort"
4+
5+
func kClosest(points [][]int, K int) [][]int {
6+
sort.Slice(points, func(i, j int) bool {
7+
return points[i][0]*points[i][0]+points[i][1]*points[i][1] < points[j][0]*points[j][0]+points[j][1]*points[j][1]
8+
})
9+
return points[:K]
10+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package k_closest_points_to_origin
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input [][]int
10+
k int
11+
expected [][]int
12+
}
13+
14+
func TestKClosest(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
input: [][]int{
18+
{1, 3},
19+
{-2, 2},
20+
},
21+
k: 1,
22+
expected: [][]int{
23+
{-2, 2},
24+
},
25+
},
26+
{
27+
input: [][]int{
28+
{3, 3},
29+
{5, -1},
30+
{-2, 4},
31+
},
32+
k: 2,
33+
expected: [][]int{
34+
{3, 3},
35+
{-2, 4},
36+
},
37+
},
38+
}
39+
for _, tc := range tests {
40+
output := kClosest(tc.input, tc.k)
41+
if !reflect.DeepEqual(output, tc.expected) {
42+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)