leetcode 458. Poor Pigs

来源:互联网 发布:linux怎么编辑文档 编辑:程序博客网 时间:2024/06/05 07:30

原题:

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.

参考解析的连接:

https://www.cnblogs.com/mux1/p/6275797.html

首先感谢楼上的博主给的答案。

我第一反应是做二进制,但是这样就算是几分的话,也不是最少的。

毕竟用维度这种能缩到最小,也是学到了。

代码很简单,不过照例还是贴一下:

int poorPigs(int buckets, int minutesToDie, int minutesToTest) {    int temp=minutesToTest/minutesToDie+1;    int amount=1;    int result=0;    while(amount<buckets)    {        result++;        amount*=temp;    }    return result;}