Given an array containing N points find the K closest points to the origin (0, 0) in the 2D plane. You can assume K is much smaller than N and N is very large.
E.g:
given array: (1,0), (3,0), (2,0), K = 2 Result = (1,0), (2,0)(result should be in ascending order by distance)
Code:
import java.util.*;
class CPoint {
double x;
double y;
public CPoint(double x, double y) {
this.x = x;
this.y = y;
}
}
public class KClosest {
/**
* @param myList: a list of myList
* @param k: the number of closest myList
* @return: the k closest myList
*/
public static CPoint[] getKNearestPoints(CPoint[] myList, int k) {
if (k <= 0 || k > myList.length) return new CPoint[]{};
if (myList == null || myList.length == 0 ) return myList;
final CPoint o = new CPoint(0, 0); // origin point
// use a Max-Heap of size k for maintaining K closest points
PriorityQueue<CPoint> pq = new PriorityQueue<CPoint> (k, new Comparator<CPoint> () {
@Override
public int compare(CPoint a, CPoint b) {
return Double.compare(distance(b, o), distance(a, o));
}
});
for (CPoint p : myList) { // Line 33
// Keep adding the distance value until heap is full. // Line 34
pq.offer(p); // Line 35
// If it is full // Line 36
if (pq.size() > k) { // Line 37
// Then remove the first element having the largest distance in PQ.// Line 38
pq.poll(); // Line 39
} // Line 40
}
CPoint[] res = new CPoint[k];
// Then make a second pass to get k closest points into result.
while (!pq.isEmpty()) { // Line 44
res[--k] = pq.poll(); // Line 45
} // Line 46
return res;
}
private static double distance(CPoint a, CPoint b) {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
}
Question:
What is time complexity for line 35, line 39, independently and separately?
What is time complexity for line 35 - 40 (As a whole) ?
What is time complexity for line 44 - 46 (As a whole) ?
What is overall time complexity for entire method getKNearestPoints(), in best, worst and average case? What if n >> k ? and what if we don't have n >> k ?
Actually these questions are a couple of question during my technical interview, but I'm still kinda confused on it. Any help is appreciated.