Find the k nearest point from the origin---FaceBook 一轮电面
There are some locations, find the K nearest one
input: [1,1],[2,3],[-1,-1], k=2
output:[1,1],[-1,-1]
Java
/*
* Defination for the location
* public class Location {
* int x;
* int y;
* int distance;
* Location(int x, int y){
* this.x = x;
* this.y = y;
* this.distance = (int) Math.sqrt(x*x + y*y);
* }
* }
*/
class Solution {
public static Location[] kNearLocation(Location[] locations, int k) {
// Queue<Location> pq = new PriorityQueue<Location>(locations.length, new Comparator<Location>(){
// @Override
// public int compare(Location l1, Location l2) {
// return (int) (l1.distance - l2.distance);
// }
// });
Queue<Location> pq = new PriorityQueue<Location>((Location l1, Location l2) -> l1.distance -l2.distance);
for (Location loc:locations) {
pq.offer(loc);
}
Location[] ans = new Location[k];
for (int i=0; i<k; i++) {
ans[i] = pq.poll();
}
return ans;
}
}