★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-rsatbskl-hv.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
Answer this question, and write an algorithm for the follow-up general case.github
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只水桶,其中有且只有一桶装的含有毒药,其他装的都是水。它们从外观看起来都同样。若是小猪喝了毒药,它会在15分钟内死去。测试
问题来了,若是须要你在一小时内,弄清楚哪只水桶含有毒药,你最少须要多少只猪?this
回答这个问题,并为下列的进阶问题编写一个通用算法。spa
进阶:rest
假设有 n 只水桶,猪饮水中毒后会在 m 分钟内死亡,你须要多少猪(x)就能在 p 分钟内找出“有毒”水桶?n只水桶里有且仅有一只有毒的桶。code
8ms
1 class Solution { 2 func poorPigs(_ buckets: Int, _ minutesToDie: Int, _ minutesToTest: Int) -> Int { 3 if buckets == 1 {return 0} 4 //每头小猪最多可测试的水桶数 5 var times = minutesToTest / minutesToDie + 1 6 var num:Int = 0 7 //假设5桶水,一头小猪一个小时内检测四个桶 8 //若是没死,则是最后一桶有毒。 9 //每增长一头小猪,能检测的桶数乘5 10 while(pow(Double(times),Double(num)) < Double(buckets)) 11 { 12 num += 1 13 } 14 return num 15 } 16 }
8ms
1 class Solution { 2 func poorPigs(_ buckets: Int, _ minutesToDie: Int, _ minutesToTest: Int) -> Int { 3 let a: Double = log(Double(minutesToTest) / Double(minutesToDie) + 1) 4 let pigs: Double = log(Double(buckets)) / a 5 return Int(pigs.rounded(.up)) 6 } 7 }
8ms
1 class Solution { 2 func poorPigs(_ buckets: Int, _ minutesToDie: Int, _ minutesToTest: Int) -> Int { 3 var pigs = 0.0 4 while pow(Double(minutesToTest / minutesToDie + 1), pigs) < Double(buckets) { 5 pigs += 1 6 } 7 return Int(pigs) 8 } 9 }
12ms
1 class Solution { 2 func poorPigs(_ buckets: Int, _ minutesToDie: Int, _ minutesToTest: Int) -> Int { 3 var pigs = 0 4 while Int(pow(Double((minutesToTest / minutesToDie) + 1), Double(pigs))) < buckets { 5 pigs += 1 6 } 7 8 return pigs 9 } 10 }