Interview Questions for a world-renowned Search Engine Company.
To be honest, this type of question is hard to solve if you do not know it. The possible way to think is: (assume there are n nodes in total, n is unknown) when I go to the x node, the information that can be used is that I have already taken step X. You need to decide whether to select the node or not, and the probability of the node being selected is 1/N.
The solution is to determine whether to select step X based on the probability of 1/X when the step X is reached. In step x + 1, the probability of step 1/(x + 1) determines whether to select step x + 1. In this way, the probability that the X is treated as the final result is that the X is selected, and the x + 1, x + 2 ,..., n) are not selected. The probability is 1/x * x/(x + 1) * (x + 1)/(x + 2)... (n-1)/n = 1/N.
ExampleCodeAs follows (input error check is not considered ):
Node * getrandomnode (node * Header)
{
Node * P = header;
Node * result = nil;
Int COUNT = 0;
For (; P! = NULL; P = p-> next)
{
Count ++;
If (0 = random (count ))
{
Result = P;
}
P = p-> next;
}
Return result;
}