面试时碰到过一次约瑟夫问题的面试,写出了算法,但是不知道是不是正确,回来验证了下。
赛赛代码:
public static void accomplishByPlainMethod(int[] array, int key){
//实现思路 : 如果谁出去后,就将数组的该位置置为0 ,在循环报数中,跳过此位置
int offset = 0; //记录当前的偏移量
int index = 0; //报数的id
int count = array.length; //数组中还剩下多少元素
if(count < 4){
System.out.println("没有必要进行该操作");
}
while(true){
if(array[index++] != 0){
if((++offset) == key){
array[index-1] = 0;
System.out.print(" "+index);
offset = 0;
count--;
}
}
if(index>=array.length){
index = 0;
}
if(count == 1){
for(int i = 0; i < array.length; i++){
if(array[i] != 0){
System.out.println();
System.out.println(" 最后一个出列的人: "+ (i+1));
}
}
break;
}
}
}