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(); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM