首页 > 代码库 > poor-pigs(非常好的思路)

poor-pigs(非常好的思路)

https://leetcode.com/problems/poor-pigs/

package com.company;


class Solution {
    // 下面第二种做法貌似是OJ原来的做法,但是是错误的
    // 看了这个解答 https://discuss.leetcode.com/topic/66856/major-flaw-in-current-algorithm-fixed
    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
        // 有5种状态
        int circle = minutesToTest / minutesToDie + 1;
        int ret = 0;
        long num = 1;
        while (num < buckets) {
            num *= circle;
            ret++;
        }
        return ret;
    }

// 以下答案不太对
public int poorPigs2(int buckets, int minutesToDie, int minutesToTest) { if (minutesToDie == 0) { return 0; } int circle = minutesToTest / minutesToDie; if (circle == 0) { return 0; } int batch = (buckets + (circle - 1)) / circle; int ret = 0; long num = 1; while (num < batch) { num *= 2; ret++; } if (num == batch && circle != 1) { return ret + 1; } else { return ret; } } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Hello!"); Solution solution = new Solution(); // Your Codec object will be instantiated and called as such: int ret = solution.poorPigs(1000, 15, 60); System.out.printf("ret:%d\n", ret); System.out.println(); } }

 

poor-pigs(非常好的思路)