1. 程式人生 > >[Swift]LeetCode458. 可憐的小豬 | Poor Pigs

[Swift]LeetCode458. 可憐的小豬 | 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只水桶,其中有且只有一桶裝的含有毒藥,其餘裝的都是水。它們從外觀看起來都一樣。如果小豬喝了毒藥,它會在15分鐘內死去。

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

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

進階:

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


 

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 }