Amazon Interview Question
Software Engineer / Developersfunction findKclosest(point x, point A[], int n)
{
MAX-HEAP m = new MAX-HEAP(A[1...k])
MAX = m.GetMax();
for(c = k+1 to n)
{
if(Distance(A[c] < MAX)
{
m.RemoveMax();
m.Insert(new Node(A[c], distance(A[c], x));
MAX = m.GetMax();
}
}
m.Print();
}
even though it's O(nlog k) in theory, it performs better in practice (depending upon the distribution of points) because I compare against a MAX variable instead of getting the MAX from heap every time.
I believe it's solvable in O(n) time using linear time order-statistic computation.
steps:
1. compute D(i) = distance of point i from p; for 1<=i<=n
2. find k-th order statistic in O(n) time. let this is point q. [REF: CORMAN book]
3. select all points r such that Distance(p,r) <= Distance(p,q).
Each of steps 1-3 takes O(n) time. So total time is O(n).
just curious is this for java programming position? or c/c++?
- Anonymous May 11, 2010