[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個(gè)罐子,其中有且只有1個(gè)是毒藥,另外其他的都是水. 現(xiàn)在用一群可憐的豬去找到那個(gè)毒藥罐. 已知毒藥讓豬毒發(fā)的時(shí)間是15分鐘, 那么在60分鐘之內(nèi),最少需要幾頭豬來(lái)找出那個(gè)毒藥罐?

解題思路:

一開(kāi)始的時(shí)候陷入思維誤區(qū),準(zhǔn)備采取二分法尋找,后來(lái)發(fā)現(xiàn)每個(gè)bucket都是一樣的,只不過(guò)15分鐘有可憐的豬遭殃的時(shí)候,才知道有毒的bucket大概會(huì)在哪里。然后就聯(lián)想到與pow函數(shù)有關(guān)。

如果只有一只豬,考慮到間隔時(shí)間為15分鐘,而測(cè)試時(shí)間是60分鐘,所以一維的情況下,一只豬可以測(cè)出最多五只桶(為什么不是60/15, 4只呢,因?yàn)槿绻懊嫠膫€(gè)測(cè)試豬都沒(méi)有死,則證明第五只桶有毒,但是不能六只桶,因?yàn)樗拇螠y(cè)試時(shí)間用完,會(huì)剩下兩只,無(wú)法確定哪只有毒)。也就是說(shuō)如果只有一只豬,可以最多檢查(測(cè)試時(shí)間/毒發(fā)時(shí)間 + 1)個(gè)桶。

擴(kuò)展到二維,則2只豬可以檢查出5*5個(gè)桶,3個(gè)豬就是5^3個(gè)桶,因此到最后就是使用pow函數(shù)來(lái)和桶數(shù)進(jìn)行比較。

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 豬的故事 There are 1000 buckets, one and only one of them con...
    MAXPUP閱讀 322評(píng)論 1 0
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,890評(píng)論 0 23
  • 你就那么等 一直等 靜默 倔強(qiáng) 高傲 你還那么等 一直等 靜默 倔強(qiáng) 卑微 他不愛(ài)你了 你知 ...
    堯光gxl閱讀 503評(píng)論 6 13
  • 我們?yōu)槭裁闯燥垼瑸槭裁春人瑸槭裁磳W(xué)習(xí), 為什么要進(jìn)步,為什么走路,為什么奔跑, 為什么思考,我們?yōu)槭裁磁Γ瑸槭?..
    DbZ31閱讀 196評(píng)論 0 0
  • 我為什么喜歡星座,這看似是現(xiàn)在每個(gè)人都關(guān)注的,星座這種東西呢,被許多人喜歡認(rèn)可,我不能免俗,對(duì)其也是相當(dāng)熱愛(ài)。首...
    你要努力呀火星寶寶閱讀 1,399評(píng)論 15 9