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)
代码:
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);
}
}
问题:
第35行和第39行的时间复杂度分别是什么?
第35 - 40行(整体)的时间复杂度是多少?
第44 - 46行(整体)的时间复杂度是多少?
在最好情况,最坏情况和平均情况下,整个getKNearestPoints()方法的总体时间复杂度是多少?如果n>>k怎么办?如果我们没有n>>k怎么办?
实际上,这些问题是我技术面试中的几个问题,但我还是有些困惑。感谢您的帮助。