1. 程式人生 > >LeetCode458. Poor Pigs(可憐的小豬)JAVA實現

LeetCode458. Poor Pigs(可憐的小豬)JAVA實現

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桶水,死亡時間15mins,測試時間1小時。需要至少死幾頭豬能找到有毒的水桶呢?

對於每頭豬,它應有5種狀態:15min、30min、45min、60min死亡和活著。假設每個桶都有對應標籤(0,1,2,3,4)對應5個狀態。

假設有5桶水,那麼只需一頭豬就可以了,就可以判斷那桶水有毒。

如果有25桶水呢?把(0~24)桶水按照5進位制進行標籤,分別對應(00,01,02,03,04,10,11,12,。。。,40,41,42,43,44).這是隻需2頭豬即可。

在t=0時刻,第一個豬喝第一位為0的桶水,第2個豬喝下第2位為0的水,在t=15時刻,第一個豬喝第一位為1的桶水,第2個豬喝下第2位為1的水,依此類推,

我們可以通過豬的死亡判斷有毒的水。

對於n桶水,已知基的情況下,b^x>=n即可,我們要找到x.

對於例題,b=4+1=5;故x=log5(1000)=5

class Solution {
    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        return (int)Math.ceil(Math.log(buckets)/Math.log(minutesToTest/minutesToDie+1));
    }
}