java例子:数组 数3退1

本文介绍了一个通过循环赛方式逐步淘汰参与者的算法实现。该算法适用于需要从多人中按特定规则筛选出最后胜者的场景,例如游戏或竞赛。通过定义Kid和KidCircle两个类,实现了参与者之间的连接,并提供了添加参与者、删除参与者的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

500个人围成一个圈子,数够3人,就退出1个,问最后剩下的是几号?

        检验先有5个人,应该留下第4个人,由于是数组,所以第四个人的下标是3.

/*achieve the  funtion :count 3 kids, the quit the third kid
use the object thinking */

public class Test{
	public static void main(String[] args) {
		KidCircle kc = new KidCircle(5);
	 	int countNum = 0;
	 	Kid k = kc.first;
	 	while(kc.count > 1){
	 		countNum ++;
	 		if(countNum ==3){
	 			countNum =0;
	 			kc.delete(k);
	 		}
	 		k = k.right;
	 	}
	 	System.out.println(kc.first.id);	
	}
}

/* define class Kid*/
class Kid{
	int id;
	Kid left;   //left is means the current kids'left kid  
	Kid right;	//right is means the current kids'right  kid
}

/* define class KidCircle*/
class KidCircle{

	int count = 0;   //mean the circles'number

	Kid first,last;  //define the circles' first kid and last kid.

	KidCircle(int n){//Constructor :new n numbers kid circle
		for(int i = 0;i<n;i++){
			add();
		}
	}

	/*add a kid in the last kids'right*/
	void add(){

		/*
		 first: new a kid;
		  id = count
		*/
		Kid k = new Kid();
		k.id = count;

		/*if  no kid in the circle ,the new kid is the first kid and is the last kid
		*/
		if(count <=0){
		first = k;
		last = k;
		k.left = k;
		k.right = k;
		}

		/*if has some kids in the circle,the new kid will stand at the last kids'right,and the new 
		kids'left is the last kid.	another: the new kids'right is the first kids'lest*/
		else{
			last.right = k;
			k.left = last;
			k.right = first;
			first.left = k;
			last = k;
			
		}
		count ++;
	}
	void delete(Kid k){
		if(count <= 0){
			return;
		}else if(count == 1){
			first = last =null;
		}else{
			k.left.right = k.right;
			k.right.left = k.left;
			if(k == first){
				first = k.right;
			}else if(k == last){
				last = k.left;
			}
		}
		count --;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值