Leetcode 458

 

我这智商,刷Leetcode简单题都不够用了,又被一道简单题虐了,思路太巧妙了。记录一下。

题目链接:https://leetcode-cn.com/problems/poor-pigs/description/

转自:https://blog.csdn.net/JackZhang_123/article/details/78775716

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桶水,死亡时间15mins,测试时间1小时。需要至少死几头猪能找到有毒的水桶呢? 
对于每头猪,它应有5种状态:15min、30min、45min、60min死亡和活着。假设每个桶都有对应标签(0,1,2,3,4)对应5个状态。 
假设有5桶水,那么只需一头猪就可以了,就可以判断那桶水有毒。 
如果有25桶水呢?把(0~24)桶水按照5进制进行标签,分别对应(00,01,02,03,04,10,11,12,。。。,40,41,42,43,44).这是只需2头猪即可。 
在t=0时刻,第一个猪喝第一位为0的桶水,第2个猪喝下第2位为0的水,在t=15时刻,第一个猪喝第一位为1的桶水,第2个猪喝下第2位为1的水,依此类推, 
我们可以通过猪的死亡判断有毒的水。 
对于n桶水,已知基的情况下,b^x>=n即可,我们要找到x. 
对于例题,b=4+1=5;故x=log5(1000)=5

注意向上取整ceil()

=====================================================分割线=======================================

如果上面思路想不懂,有个更简单的解释,如果每个猪有m个状态,把所有水桶看成高纬度等边矩阵,每个猪负责遍历一个维度,那么如果所有猪都健康,那么它们能锁定一个位置的水桶没毒,如果有一猪死了,那么直接抽出它当前维度对应值的水桶,其他都过关,并不会遍历不完。

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <cmath>

using namespace std;

class Solution 
{
public:
    int poorPigs(int buckets, int minutesToDie, int minutesToTest)
    {
        if (buckets == 1)
            return 0;

        int base = minutesToTest / minutesToDie + 1;
        int r = 1;
        for (int i = 1;; i++)
        {
            r *= base;
            if (r >= buckets)
                return i;
        }
        return 0;
    }
};

只能说代码是简单的,思路确实比不上别人,还是刷题刷的少。。

上个python代码吧:

#encoding=utf-8
import numpy as np


class Solution(object):
    def poorPigs(self, buckets, minutesToDie, minutesToTest):
        """
        :type buckets: int
        :type minutesToDie: int
        :type minutesToTest: int
        :rtype: int
        """
        times = minutesToTest / minutesToDie + 1
        ans = 0
        tmp = buckets * 1.0
        while tmp > 1:
            tmp /= times
            ans += 1
        return ans

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值