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.
class Solution {
public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
if (buckets <= 1 || minutesToDie > minutesToTest) { return 0; }
int pigs = 0;
int rate = minutesToTest / minutesToDie + 1;
while (Math.pow(rate, pigs) < buckets) {
pigs++;
}
return pigs;
}
}

本文探讨了一个经典的数学问题:如何利用最少数量的猪,在有限时间内找出唯一有毒的水桶。通过算法设计,给出了针对不同桶数、死亡时间和测试周期情况下的最优解决方案。
5万+

被折叠的 条评论
为什么被折叠?



