458. 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.

Java:

package com.pku.leetcode.study;

public class Solution458 {
    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        return (int) (Math.ceil(Math.log(buckets) / Math.log(minutesToTest / minutesToDie + 1)));
    }
}

C++:

class Solution {
public:
       int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
           if (buckets == 1) return 0;
           int capacity = minutesToTest / minutesToDie + 1;
           int dimention = 0, product = 1;
           while (product < buckets) {
                 product *= capacity;
                 ++dimention;      
           }    
           return dimention;
       }    
};

Python:

class Solution(object):
    def poorPigs(self, buckets, minutesToDie, minutesToTest):
        """
        :type buckets: int
        :type minutesToDie: int
        :type minutesToTest: int
        :rtype: int
        """
        pigs = 0
        while (minutesToTest / minutesToDie + 1) ** pigs < buckets:
            pigs += 1
        return pigs

你可能感兴趣的:(数据结构&算法,Leetcode)