-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathleetcode-973-KClosestPointsToOrigin.js
61 lines (51 loc) · 1.41 KB
/
leetcode-973-KClosestPointsToOrigin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// https://leetcode.com/problems/k-closest-points-to-origin/
// p: array of ints && int k
// r: array of k arrays
// e:
// 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]].
var kClosest = function (points, k) {
points.sort(
(a, b) =>
Math.sqrt(a[0] ** 2 + a[1] ** 2) - Math.sqrt(b[0] ** 2 + b[1] ** 2)
);
return points.slice(0, k);
};
// kClosest(
// [
// [1, 3],
// [-2, 2],
// ],
// 1
// );
kClosest(
[
[3, 3],
[5, -1],
[-2, 4],
],
2
);
// kClosest([
// [0, 1],
// [1, 0],
// ]);
// var kClosest = function (points, k) {
// // [[],[],[]]
// // calculate the distance between each point to ori
// for (let i = 0; i < points.length; i++) {
// let point = points[i];
// let distance = Math.sqrt(point[0] ** 2 + point[1] ** 2);
// points[i] = [distance, point];
// }
// // compare them to get the 1st min, 2nd min .... kth min
// points.sort((a, b) => a[0] - b[0]);
// // return [] of k maxes
// console.log(points.slice(0, k).map((e) => e[1]));
// return points.slice(0, k).map((e) => e[1]);
// };