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

1.Description

You have  n  coins ( n  may be even or odd) such that  n1  coins 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 be  O(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;i<mid;i++)
    		{
    			LeftSum+=coins[i]; //iteratively get the weight of the left side coins
    			RightSum+=coins[i+mid-left];
    		}
//if the weight of left side is bigger than right side, the special coin should be in the left side
    	if(LeftSum>RightSum)   
    	{
    		right=mid;
    		findCoin(coins,left,right);
    	}
    	else if(LeftSum<RightSum)
    	{
    		left=mid;
    		findCoin(coins,left,right);
    	} 
//if the weight of left side is equal to right side, the special coin should be the last remaining one
    	else if(LeftSum==RightSum)
    	{
    		System.out.println("The special coin is coins["+right+"]");
    	}
    	}
    }
 
    public static void main(String[] args) {
    	int coins1[]={1,1,1,1,1,1,1,1,1,2};
    	int coins2[]={1,1,1,1,2,1,1,1,1};
    	int left1=0,right1=coins1.length-1;
    	findCoin(coins1,left1,right1);
    	int left2=0,right2=coins1.length-1;
    	findCoin(coins2,left2,right2);
    }
}

Screenshot of the result:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值