[Swift]LeetCode458. 可憐的小豬 | Poor Pigs

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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 }
相關文章
相關標籤/搜索