[LeetCode] 458. Poor Pigs_Easy tag: Math

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.

这个题目很巧妙, 我们利用@StefanPochmannSolution和解释, 得到了通用的表达式, 也就是 (minutesToTest//minutesToDie + 1)**pigs >= buckets 中最小的pigs

note: 这里的edge case 是 minutesToTest >= minutesToDie

Code

class Solution(object):
def poorPigs(self, buckets, minutesToDie, minutesToTest):
"""
:type buckets: int
:type minutesToDie: int
:type minutesToTest: int
:rty
"""
      
     if minutesToTest < minutesToDie: return -1
pigs = 0
while (minutesToTest//minutesToDie +1)**pigs < buckets:
pigs += 1
return pigs
上一篇:CLR类型设计之方法与构造器


下一篇:Webwork【02】前端OGNL试练