题目:0,1,,,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字,求出这个圆圈里剩下的最后一个数字。eg,0,1,2,3,4这五个数字,从数字0开始每次删除第3个数字,则删除依次为2,0,4,1,最后剩下的数字是3
分析:可用环形链表来模拟圆圈,剑指offer上有讲解利用递归公式,还没看懂,持续更新。。。
import java.util.*;
public class wr45YueSeFu {
public static int LastRemaining_Solution(int n, int m){
if(n<1 || m<1){
return 0;
}
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<n;i++){
list.add(i);
}
int index=(m-1)%list.size();
while(list.size()!=1){
list.remove(index);
index=(index+m-1)%list.size();
}
return list.get(0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(LastRemaining_Solution(5,3));
}
}
看到有人用数组来模拟,
// 数组,每次当前元素的移动都伴随着计步器加1,当步数等于m时,当前元素设为-1,表示已经被删除
public static int byArray(int n,int m){
if(n<1 || m<1){
return -1;
}
int []a=new int[n];
int curIndex=-1;//当前遇到对象索引
int count=0;
int num=n;
while(num>0){
curIndex++;//移动到上次被删除元素的下一个元素
// 如果目前是最后一个了,则从头开始,模拟环
if(curIndex==n){
curIndex=0;
}
// 如果目前已经被删除,跳过,不计数
if(a[curIndex]==-1){
continue;
}
count++;
if(count==m){
a[curIndex]=-1;
count=0;
num--;
}
}
return curIndex;
}