20200124

# 458 Poor Pigs 可憐的小豬

__Description__:

There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.

You can feed the pigs according to these steps:

Choose some live pigs to feed.

For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.

Wait for minutesToDie minutes. You may not feed any other pigs during this time.

After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.

Repeat this process until you run out of time.

Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.

__Example:__

Example 1:

Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60

Output: 5

Example 2:

Input: buckets = 4, minutesToDie = 15, minutesToTest = 15

Output: 2

Example 3:

Input: buckets = 4, minutesToDie = 15, minutesToTest = 30

Output: 2

__Constraints:__

1 <= buckets <= 1000

1 <= minutesToDie <= minutesToTest <= 100

__題目描述__:

有 buckets 桶液體,其中 正好 有一桶含有毒藥,其餘裝的都是水。它們從外觀看起來都一樣。爲了弄清楚哪隻水桶含有毒藥,你可以喂一些豬喝,通過觀察豬是否會死進行判斷。不幸的是,你只有 minutesToTest 分鐘時間來確定哪桶液體是有毒的。

餵豬的規則如下:

選擇若干活豬進行餵養

可以允許小豬同時飲用任意數量的桶中的水,並且該過程不需要時間。

小豬喝完水後,必須有 minutesToDie 分鐘的冷卻時間。在這段時間裏,你只能觀察,而不允許繼續餵豬。

過了 minutesToDie 分鐘後,所有喝到毒藥的豬都會死去,其他所有豬都會活下來。

重複這一過程,直到時間用完。

給你桶的數目 buckets ,minutesToDie 和 minutesToTest ,返回在規定時間內判斷哪個桶有毒所需的 最小 豬數。

__示例 :__

示例 1:

輸入:buckets = 1000, minutesToDie = 15, minutesToTest = 60

輸出:5

示例 2:

輸入:buckets = 4, minutesToDie = 15, minutesToTest = 15

輸出:2

示例 3:

輸入:buckets = 4, minutesToDie = 15, minutesToTest = 30

輸出:2

__提示:__

1 <= buckets <= 1000

1 <= minutesToDie <= minutesToTest <= 100

__思路__:

每頭豬的試驗次數 count爲 minutesToTest / minutesToDie + 1

豬的數量爲 log(count)(buckets)

時間複雜度O(1), 空間複雜度O(1)

__代碼__:

__C++__:

```C++

class Solution

{

public:

    int poorPigs(int buckets, int minutesToDie, int minutesToTest)

    {

        return buckets == 1 ? 0 : ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));

    }

};

```

__Java__:

```Java

class Solution {

    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {

        if (buckets <= 1) return 0;

        int time = minutesToTest / minutesToDie + 1, result = 1;

        while (Math.pow(time, result) < buckets) ++result;

        return result;

    }

}

```

__Python__:

```Python

class Solution:

    def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:

        return 0 if buckets == 1 else ceil(log(buckets) / log(minutesToTest // minutesToDie + 1))

```

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章