[LeetCode][Python]458. Poor Pigs

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个罐子,其中有且只有1个是毒药,另外其他的都是水. 现在用一群可怜的猪去找到那个毒药罐. 已知毒药让猪毒发的时间是15分钟, 那么在60分钟之内,最少需要几头猪来找出那个毒药罐?

解题思路:

一开始的时候陷入思维误区,准备采取二分法寻找,后来发现每个bucket都是一样的,只不过15分钟有可怜的猪遭殃的时候,才知道有毒的bucket大概会在哪里。然后就联想到与pow函数有关。

如果只有一只猪,考虑到间隔时间为15分钟,而测试时间是60分钟,所以一维的情况下,一只猪可以测出最多五只桶(为什么不是60/15, 4只呢,因为如果前面四个测试猪都没有死,则证明第五只桶有毒,但是不能六只桶,因为四次测试时间用完,会剩下两只,无法确定哪只有毒)。也就是说如果只有一只猪,可以最多检查(测试时间/毒发时间 + 1)个桶。

扩展到二维,则2只猪可以检查出5*5个桶,3个猪就是5^3个桶,因此到最后就是使用pow函数来和桶数进行比较。

import math
class Solution(object):
    def poorPigs(self, buckets, minutesToDie, minutesToTest):
        """
        :type buckets: int
        :type minutesToDie: int
        :type minutesToTest: int
        :rtype: int
        """
        time = minutesToTest/minutesToDie + 1
        res = 0
        while(math.pow(time, res)< buckets):
            res=res+1

        return res


if __name__ == "__main__":
    sol = Solution()
    print sol.poorPigs(1000, 15, 60)
    print sol.poorPigs(5, 15, 60)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 猪的故事 There are 1000 buckets, one and only one of them con...
    MAXPUP阅读 2,555评论 1 0
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,496评论 0 23
  • 你就那么等 一直等 静默 倔强 高傲 你还那么等 一直等 静默 倔强 卑微 他不爱你了 你知 ...
    尧光gxl阅读 3,385评论 6 13
  • 我们为什么吃饭,为什么喝水,为什么学习, 为什么要进步,为什么走路,为什么奔跑, 为什么思考,我们为什么努力,为什...
    DbZ31阅读 1,499评论 0 0
  • 我为什么喜欢星座,这看似是现在每个人都关注的,星座这种东西呢,被许多人喜欢认可,我不能免俗,对其也是相当热爱。首...
    你要努力呀火星宝宝阅读 5,285评论 15 9

友情链接更多精彩内容