drop eggs
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;
}
}
推荐阅读
-
HTML5+CSS3实现拖放(Drag and Drop)示例
-
drop,truncate与delete的区别
-
详解MySQL中DROP,TRUNCATE 和DELETE的区别实现mysql从零开始
-
oracle drop table(表)数据恢复方法
-
sqlserver 日志恢复方法(搞定drop和truncate)
-
create database ,drop database ,show Databases,use 数据库 ,怎么使用?
-
create table,show tables,describe table,DROP TABLE,ALTER TABLE ,怎么使用?
-
详解HTML5中的拖放事件(Drag 和 drop)
-
突袭HTML5之Javascript API扩展4—拖拽(Drag/Drop)概述
-
HTML5 拖放(Drag 和 Drop)详解与实例代码