??
Introduction
??
Common Joseph Ring problem useful loop-linked list do, useful array to do, here to provide a mathematical formula to do, thus, many computer problems if the final use of mathematical knowledge, time complexity will be greatly reduced
??
Analyze problems
??
First of all we on the 0 to n1 Delete the first number for analysis, the first deleted number must be the number of m-1, because No. 0 number 1, 1th number of 2,m-1 number of M, then should be deleted m-1 number, set the m-1 number is the K number, This is done because the back can be expanded to extend to m-1%n=k
??
The remaining numbers are reordered by sequence as follows
??
Because the deletion is K, then the first one is K+ 1, this is very good understanding
??
Suppose we set the output of the F function to be the original number in n , the number of m per time, and the last left
??
And now delete K, only n1 numbers, each time a few m, the last number left is F ' (n-1,m)
??
??
How to establish the relationship between F ' and F. ' ?
??
We do a mapping of the numbers after reordering
??
??
The mapping is
P (x)--> Y::: y= (x-k-1)%n
??
Then the mapping is the same as the original problem, that is F(n-1,m)
??
i.e. P(f ' (n-1,m) =f (n-1,m)
??
And now we only have a relationship between F(n,m) and F ' (N-1,M)
??
So we need to switch again, and we'll find the inverse of the map.
??
??
and the inverse map of the map p is
??
O (Y)-->x x= (y+k+1)%n
??
Where K can replace k%n= (m-1)%n
??
i.e. o (y)-->x x= (y+m)%n
??
Corresponds to the relationship between the previous F (n-1,m) and F ' (n-1,m)
??
F ' (n-1,m) =f (n-1,m) +m%n
??
and
??
F (n,m) =f ' (n-1,m)
??
So we have the relationship between F (n,m) and F ' (n-1,m) , and also the relationship between F (n1, M) and F ' (n-1,m)
??
The pre-loaded formula is pushed to get
??
??
Solve the problem
??
static int Lastremain (int n, int m) {
int last = 0;
if (N < 1 | | m < 1) {
return-1;
}
for (int i = 2; I <= n; i++)
Last = (last + m)% i;
return last;
}
??
A report on the problem of sword-pointing offer (Java edition)--Joseph Ring 45