Created
May 4, 2022 14:19
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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