Java中硬币枚举_找出一堆硬币中较重的一个(java 算法)

1.Description

You havencoins (nmay be even or odd) such thatn−1coins are of the same weight and one has different weight. You have a balance scale; you can put any number of coins on each side of the scale at one time, and it will tell you if the two sides weigh the same, or which side is lighter if they do not weigh the same.Outline an algorithm for finding the coin with different weight for each of the following conditions. The number of weighings using your algorithm in each case should beO(logn). You know that one coin weighs more than the others.

2.Algorithm

(1)If the number of coins is even, split them into two parts. If the number is odd, split them into two parts and one coin.

Get the weight of the two parts. The coin which weighs more than other must lie in the part which weighs more.

In the side which weighs more, recursively call step 1. If the weight of two parts are the same, the special coin is the last remaining one.

3.Implementation

public class Coin {

public static void findCoin(int coins[],int left, int right) {

int mid=(int) Math.ceil((left+right)/2); //get the upper limit

int LeftSum=0,RightSum=0;

if(left==right)

{

System.out.println("The special coin is coins["+right+"]");

}

else if(right-left==1)

{

if(coins[left]>coins[right])

{

System.out.println("The special coin is coins["+left+"]");

}

else if(coins[left]>coins[right])

{

System.out.println("The special coin is coins["+right+"]");

}

}

else

{

for(int i=left;iRightSum)

{

right=mid;

findCoin(coins,left,right);

}

else if(LeftSum

Screenshot of the result:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值