I. Title Description:
Leetcode-cn.com/problems/ma… We have a list of points that are points on the plane. I want to find K points that are closest to the origin (0, 0). (Here, the distance between two points on the plane is the Euclidean distance.) You can return the answers in any order. The answer is guaranteed to be unique except for the order of the point coordinates.
**** Example 1:
Points = [[1,3],[-2,2]], K = 1 The distance between (1, 3) and the origin is SQRT (10), and the distance between (-2, 2) and the origin is SQRT (8), and since SQRT (8) is less than SQRT (10), (-2, 2) is closer to the origin. We only need the nearest K = 1, so the answer is [[-2,2]].Copy the code
Ii. Analysis of Ideas:
- Direct violence,sort + map method is a bit stupid but still AC
Iii. AC Code:
/ * * *@param {number[][]} points
* @param {number} k
* @return {number[][]}* /
var kClosest = function(points, k) {
const res = []
let min = Number.MAX_SAFE_INTEGER
const map = {}
for(let i=0; i<points.length; i++){const [x,y] = points[i]
const dis = Math.pow(x,2) + Math.pow(y,2)
if(map[dis]){
map[dis].push(points[i])
}else{
map[dis] = [points[i]]
}
}
const keys = []
for(let key in map){
keys.push(key)
}
keys.sort((a,b) = >a-b)
for(let i=0; i<keys.length; i++){for(let j=0; j<map[keys[i]].length; j++){if(k ===0) {return res
}
res.push(map[keys[i]][j])
k--
}
}
return res
};
Copy the code