K Closest Points to Origin LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} points
3
* @param {number} k
4
* @return {number[][]}
5
*/
6
var kClosest = function (points, k) {
7
let res = [];
8
let hashMap = new Map();
9
for (let i = 0; i < points.length; i++) {
10
//store the distance and the index of the points in a map
11
const dis = calcDis(points[i]);
12
hashMap.set(i, dis);
13
}
14
//sort the map by its distance to the origin
15
const hashMapNew = new Map([...hashMap].sort((a, b) => a[1] - b[1]));
16
//use the index sorted by distance to get the result
17
let i = 0;
18
for (const x of hashMapNew.keys()) {
19
//do it k times
20
if (i === k) break;
21
res.push(points[x]);
22
i++;
23
}
24
return res;
25
};
26
var calcDis = (b) => {
27
return Math.sqrt(Math.pow(b[0], 2) + Math.pow(b[1], 2));
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0