Reputation: 4472
Suppose that we have a set of number as P = { p1, p2, p3, ..., pn }
( length(P) = n
) and choose a number as q
. So I want to find an algorithm to get the nearest member of set P
to q
. So the question is: What structure is appropriate to keep data ( p1, p2, ...
) and algorithms to find nearest member of P to q in O(1)
time complexity.
Upvotes: 2
Views: 1259
Reputation: 115520
The only way I can think of getting O(1)
time complexity is if you can use O(pn)
space and O(pn)
time to preorder P and allocate values in a pn
size array.
Preorder P
so p1
is the minimum and pn
is the maximum (I assume that they are integers.) Then store in an array with size (pn-p1+1)
the values:
A(p1) = p1
for i = 2 to n
for q = p(i-1)+1 to (p(i-1)+p(i))/2
A(q) = p(i-1)
for q = (p(i-1)+p(i))/2 to p(i)
A(q) = p(i)
Then all you have to check for a certain q
is:
if q < A(p1)
closest = A(p1)
elif q > A(pn)
closest = A(pn)
else
closest = A(q)
Upvotes: 1
Reputation: 24546
Upvotes: 6