0458. Poor Pigs

458. Poor Pigs #

题目 #

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 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 ,返回在规定时间内判断哪个桶有毒所需的 最小 猪数。

解题思路 #

使用数学方法,以 minutesToDie=15, minutesToTest=60, 1 只小猪为例,可以测试 5 只桶

  • 0-15 小猪吃第一个桶中的液体,如果死去,则第一个桶有毒,否则继续测试
  • 15-30 小猪吃第二个桶中的液体,如果死去,则第二个桶有毒,否则继续测试
  • 30-45 小猪吃第三个桶中的液体,如果死去,则第三个桶有毒,否则继续测试
  • 45-60 小猪吃第四个桶中的液体,如果死去,则第四个桶有毒
  • 如果最后小猪没有死去,则第五个桶有毒

所以一只小猪在 minutesToDie 和 minutesToTest 时间一定的情况下可以最多判断 base = minutesToTest / minutesToDie + 1 个桶

假设小猪的数量是 num,那么 pow(base, num) >= buckets,根据对数运算规则,两边分别取对数得到: num >= Log10(buckets) / Log10(base)

代码 #


package leetcode

import "math"

func poorPigs(buckets int, minutesToDie int, minutesToTest int) int {
	base := minutesToTest/minutesToDie + 1
	return int(math.Ceil(math.Log10(float64(buckets)) / math.Log10(float64(base))))
}

⬅️上一页

下一页➡️

Calendar Jan 10, 2022
Edit Edit this page
本站总访问量:  次 您是本站第  位访问者