Algorithm to find special point k in O(n log n) time
Give an n log n time lower bound for an algorithm to check if a set of points has a special point k.
k is defined as:
for a set A of points, if for every point m in A, there is a point q in A such that k is in the middle of the line segment mq such a k does not h开发者_JS百科ave to belong to A.
For example, this set has a special point k = (0.5, 0.5) for a set of four points (1,0), (0,1), (1,1), (0,0).
I was totally poker faced when they asked me this, nothing came to my mind. I guess it needs some strong geometrical background.
O(nlogn)
solution (I'm still not clear why you're looking for a lower bound solution. You might as well just do an exhaustive check, and then just run an nlogn loop to make sure of the lower bound. Not very difficult. I think you must mean upper bound):
Find the only valid candidate point by averaging all the points. I.e. summing their co-ordinates and dividing by the number of points. If such a k exists, this is it. If no such k exists, we'll find that the point found is invalid in the final step.
Create a new array (set) of points, where we shift our axes so they centre on the point k. I.e. if k = (xk,yk), a point (x,y) will become (x-xk, y-yk). Sort the points according to the ratio x/y and the norm sqrt(x2+y2). As the next step shows, it doesn't matter how this sort is done, i.e. which is the main criterion and which the secondary.
We could search for each point's complement, or better, simply traverse the array and verify that every two adjacent points are indeed complements. I.e. if this is a solution then every two complementary points in this new array are of the form (x,y) and (-x,-y) since we re-centered our axes, which means they have the same ratio ("gradient") and norm, and after the sort, must be adjacent.
If k is not valid, then the there is a point who we will arrive at in this traversal, and find that it's neighbour is not of the right/complementary form ==> there is no such k.
Time =
O(n)
for finding the candidate k +
O(n)
for building the new array, since each new point can be calculated in O(1) +
O(nlogn)
for the sort +
O(n)
for the verifying traversal
= O(nlogn)
I'd say you just compute the center of mass (having removed duplicates first) and check if it is your k
. Probably the only thing that cause it to be O(n log n)
would be searching for a point at specified location.
精彩评论