Josephus问题(基于数组的实现)

while循环没弄好(没起作用),应该用while(people.length>=1)代替while(counter!=M),退出循环后再输出people[0];不过不再实现了。

实现一个基于环形链表数据结构的环形队列来做会更好一些。

package Algorithm;

import edu.princeton.cs.algs4.*;

public class Josephus {
	public static void main(String[] args){
		//完成准备工作
		int N=StdIn.readInt();
		int M=StdIn.readInt();
		int[] people=new int[N];
		for(int i=0;i<N;i++)
			people[i]=i;
		//从数组的第一个元素往后面依次计数直至计数器的值等于M,取出当前数组索引对应的元素,
		//如果到达数组最末,返回数组头继续计数。每次取出元素后数组长度缩小一位。
		
		//index指向数组索引,counter表明报(计)数器
		int index=0,counter=1;
		while(counter!=M){
			counter++;
			if(index==people.length-1)
				index=0;
			else
				index++;
			if(counter==M){
				//找到人以后,将people数组内该索引处的元素清除,数组长度减一
				StdOut.println(people[index]);
				int[] alive =new int[people.length-1];
				for(int n=0;n<people.length-1;n++){
					if(n<index)
						alive[n]=people[n];
					else
						alive[n]=people[n+1];
				}
				if(people.length==1)
					break;
				people=alive;
				//index处的元素撤去,此时counter、index均指向这个"死"元素,在下一次循环中counter、index要加1,故此处如此处理
				counter=0;
				index--;
			}
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值