约瑟夫环问题(基本和进阶)
2019-03-01 本文已影响0人
柴崎越
一,问题描述
![](https://img.haomeiwen.com/i16452800/75291a4bf46a984a.png)
二,一般解法
public static Node josephusKill1(Node head,int m)
{
if(head ==null||head.next==head||m<1)
{
return head;
}
Node last=head;
while(last.next!=head)
{
last=last.next;
}
int count=0;
while(head!=last)
{
if(++count==m)
{
last.next=head.next;
count=0;
}else{
last=last.next;
}
head=last.next;
}
return head;
}
每一个结点,都要走m步,所有时间复杂度为O(m*n),进阶解法要求做到时间复杂度O(n)
三,进阶解法
3.1 分析
当给定结点的数量和报的数就可以确定最后幸存的结点
base case:当只有一个结点时,结点的编号为1,所以只要确定f(i)和f(i-1)的关系,就可以得出f(N)的结果(即在节点个数为n的情况下的幸存的结点的编号)
![](https://img.haomeiwen.com/i16452800/58cf1406894b8da7.png)
![](https://img.haomeiwen.com/i16452800/8288a35e8478c681.png)
![](https://img.haomeiwen.com/i16452800/32bf7a72cb7de3ba.png)
设函数名为getLive(int i(元素的个数),int m(报数))
函数体
{
}