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

自己的思维很局限,看到大神的解释不得不膜拜
https://discuss.leetcode.com/topic/67666/another-explanation-and-solution

解法很简单,如下

class Solution {
    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        int pigs=0;
        while(Math.pow(minutesToTest/minutesToDie+1,pigs)<buckets){
            pigs+=1;
        }
        return pigs;
    }
}

猜你喜欢

转载自blog.csdn.net/srping123/article/details/77445231