1. 程式人生 > >LeetCode--458--可憐的小豬

LeetCode--458--可憐的小豬

測試 設有 tco type int etc 描述 div urn

問題描述:

有1000只水桶,其中有且只有一桶裝的含有毒藥,其余裝的都是水。它們從外觀看起來都一樣。如果小豬喝了毒藥,它會在15分鐘內死去。

問題來了,如果需要你在一小時內,弄清楚哪只水桶含有毒藥,你最少需要多少只豬?

回答這個問題,並為下列的進階問題編寫一個通用算法。

進階:

假設有 n 只水桶,豬飲水中毒後會在 m 分鐘內死亡,你需要多少豬(x)就能在 p 分鐘內找出“有毒”水桶?n只水桶裏有且僅有一只有毒的桶。

方法:假設5桶水,一個小時內一頭豬檢測四個桶,如果沒死,肯定是最後一桶有毒。每增加一頭,能檢測的桶數乘5,pow(5,num) > buckets

 1 class Solution(object):
2 def poorPigs(self, buckets, minutesToDie, minutesToTest): 3 """ 4 :type buckets: int 5 :type minutesToDie: int 6 :type minutesToTest: int 7 :rtype: int 8 """ 9 times = minutesToTest / minutesToDie + 1 #每頭豬最多可測試的水桶數 10 num = 0
11 while pow(times,num) < buckets: 12 num = num + 1 13 return num

2018-10-03 21:47:29

LeetCode--458--可憐的小豬