欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

drop eggs

程序员文章站 2022-05-05 17:38:14
...

There is a building of n floors. If an egg drops from the k th floor or above, it will break. If it's dropped from any floor below, it will not break.

You're given two eggs, Find k while minimize the number of drops for the worst case. Return the number of drops in the worst case.

Example

Example 1:

Input: 100
Output: 14

Example 2:

Input: 10
Output: 4

Clarification

For n = 10, a naive way to find k is drop egg from 1st floor, 2nd floor ... kth floor. But in this worst case (k = 10), you have to drop 10 times.

Notice that you have two eggs, so you can drop at 4th, 7th & 9th floor, in the worst case (for example, k = 9) you have to drop 4 times.

思路:目标就是找到一种策略,使得无论哪一楼破裂,我们找到那一层所用到的数目都是一样的,也就是怎么将N怎么分成几段,然后每次找的次数都是一样的。

例如:总数是10,那么我们从4,7,9测试,所得到的次数都是4次。

4破裂 1,2,3, 总共1+3 = 4次;

7破裂,4没破裂,5,6,总共也是4次

9破裂,4,7没破裂,8,总共也是4次。

如果分的原则就是第x , 第x+ (x-1) ,第X+(x-1) +(x-2)  ....

也就是x +(x-1) +(x-2) +...+2+1 >= n

我们就是要找到这个x是多少第一次使得公式成立。

https://www.youtube.com/watch?v=NGtt7GJ1uiM

public class Solution {
    /**
     * @param n: An integer
     * @return: An integer
     */
     // x + (x-1) + (x-2) + (x-3) + .. + 1 >=n;
    public int dropEggs(int n) {
        if(n <= 0) return 0;
        
        long index = 1;
        while(index*(index+1) / 2 < n){
            index = index*2;
        }
        
        long start = 1;
        long end = index;
        
        // find first x which let x*(x+1) / 2 >= n;
        while(start + 1 < end) {
            long mid = start +(end - start) / 2;
            if(mid*(mid+1) / 2 > n){
                end = mid;
            } else {
                start = mid;
            }
        }
        
        if(start*( start+1) / 2 >= n){
            return (int)start;
        }
        return (int)end;
    }
}

 

 

 

 

相关标签: Binary Search