I was going to go to bed after the 01 matrix, but I couldn’t resist peeking at the next one.
Given a list of [x,y] coordinates, return the k points closest to the origin, rated “medium”.
I read it over and thought, you just need to compute the distances for each point, sort by distance, and then return the first k items. Am I reading this wrong? Is it harder than this? Am I missing something?
So I read it over again. No, no weird input or output format. No tricky limits or ranges.
Shrug, okay.
// Convenience structure to make it stupid easy.
type point struct {
x int
y int
dist float64
}
func kClosest(points [][]int, k int) [][]int {
// this seems like I'd sort the points by distance and return the
// slice containing the right number of items...and yeah, that was it.
// Create a slice to put the points and distances in.
distancedPoints := []point{}
for i := 0; i < len(points); i++ {
// stash coordinates
p := point{
x: points[i][0],
y: points[i][1],
}
// Go's sqrt wants float64, so convert the coords to float64
// and do the calculation that's even spelled out in the description.
X := float64(p.x)
Y := float64(p.y)
p.dist = math.Sqrt(X * X + Y * Y)
// All saved together.
distancedPoints = append(distancedPoints, p)
}
// sorted in increasing distance...
sort.Slice(distancedPoints,
func(i, j int) bool {
return distancedPoints[i].dist < distancedPoints[j].dist
})
// Take the first k points. We create and return the new slice
// because we have to get rid of the distance.
out := [][]int{}
for i := 0; i <= k-1; i++ {
out = append(out, []int{distancedPoints[i].x, distancedPoints[i].y})
}
// That was it. Really.
return out
}
I really don’t get why this is a medium. I did have to check the type on Math.sqrt, and double-check the sort.Slice syntax, but in terms of what to do, this is not a medium.
97th percentile on speed, 28th on memory. I suppose you could sort parallel arrays for memory savings, but why bother? It just makes the code more complex without adding a lot of value.
Leave a Reply
You must be logged in to post a comment.