973.最接近原点的K个点
var kClosest = function(points, k) {
let n=points.length;
if(k>n){
return points;
}
let dists=new Array(n).fill(null);
for(let i=0;i<n;++i){
dists[i]=dist(points[i])
}
dists.sort((a,b)=>a-b);
let distK=dists[k-1];
let ans=[]
let t=0;
for(let i=0;i<n;i++){
if(dist(points[i])<=distK){
ans[t++]=points[i];
}
}
return ans
};
function dist(point){
return point[0]*point[0]+point[1]*point[1]
}
//class 版本
class Solution {
kClosest(points, K) {
const N = points.length;
const dists = new Array(N);
for (let i = 0; i < N; ++i)
dists[i] = this.dist(points[i]);
dists.sort((a, b) => a - b);
const distK = dists[K - 1];
const ans = [];
let t = 0;
for (let i = 0; i < N; ++i)
if (this.dist(points[i]) <= distK)
ans[t++] = points[i];
return ans;
}
dist(point) {
return point[0] * point[0] + point[1] * point[1];
}
}
const s = new Solution();
const points = [[3, 3], [5, -1], [-2, 4]];
console.log(s.kClosest(points, 2));
//简化版
var kClosest = function(points, k) {
// 直接在points上进行原地操作,根据欧几里得距离的平方进行排序
points.sort((a, b) => (a[0]*a[0] + a[1]*a[1]) - (b[0]*b[0] + b[1]*b[1]));
// 返回前k个元素
return points.slice(0, k);
};
1
标签:973,个点,原点,points,let,dists From: https://www.cnblogs.com/KooTeam/p/18678948