Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created May 4, 2022 14:19
Show Gist options
  • Save Turskyi/8aeb06f0cb959905912ee357fd16aea6 to your computer and use it in GitHub Desktop.
Save Turskyi/8aeb06f0cb959905912ee357fd16aea6 to your computer and use it in GitHub Desktop.
Given a list of points, return the k closest points to the origin (0, 0).
fun kClosest(points: Array<IntArray>, k: Int): Array<IntArray> {
return points.sortedWith(comparator = compareBy { it[0] * it[0] + it[1] * it[1] }).take(k).toTypedArray()
}
/*
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Ex: Given the following points and value of k…
points = [[1,1],[-2,-2]], k = 1, return [[1, 1,]].
Ex:
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
Ex: Given the following points and value of k…
points = [[1,1],[-2,-2]], k = 1, return [[1, 1,]].
Ex:
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
* */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment