leetcode 458. Poor Pigs

There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.

Answer this question, and write an algorithm for the follow-up general case.

Follow-up:

If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison.


1000桶有一只是有毒的,用最少的猪在一小时内找出这个桶,每只猪喝完桶里的水15分钟会死。

N桶水,喝了毒药的猪在m分钟内挂掉,请问在p分钟内找出有毒的水,至少需要多少只猪(x)?

一维里一只猪一小时可以检验5桶水(前四桶没毒第五桶肯定有毒),那么二维里两只猪就可以检测5*5 25只桶 每次喝一列/一行每行每列会相交在一个点这个点就是那个有毒的桶,如下图坐标,

竖坐标(1 6 11 16 21) (2 7 12 17 22) (3 8 13 18 23) (4 9 14 19 24) 

横坐标(1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15) (16 17 18 19 20)  这样子排列好后混着吃死的那个肯定会有两只猪死就能确定那个桶,如果没有猪死那就是25这个桶。

1   2   3   4   5

6   7   8   9  10

11 12 13 14 15

16 17 18 19 20

21 22 23 24 25

同理三维的话每只猪和一个面(25桶)三个面会相交于一个点,这个点就是那个桶,同理上升的n维需要n个左边点就可以确定改点。所以5^n大于需要求得通就可以了。


Follow-up:通过上述分析容易得出

(⌊ p/m ⌋+1)^x>N    x就是所需的猪

class Solution {
    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        int pigs=0;
        while(Math.pow((minutesToTest/minutesToDie+1),pigs)<buckets){
            pigs++;
        }
        return pigs;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值