【发布时间】:2020-02-19 13:06:12
【问题描述】:
给定一个表示正方形块的整数 A。每个方块的高度为 1。任务是使用这些方块创建一个最大高度的楼梯。第一个楼梯只需要一个街区,第二个楼梯需要两个街区,依此类推。查找并返回楼梯的最大高度。
您的提交因以下输入而失败:A : 92761
您的函数返回以下内容:65536
预期返回值:430
Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…
Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.
代码
public int solve(int A) {
int l=1,h=A,T=2*A;
while(l<=h)
{
int mid=l+(h-l)/2;
if((mid*(mid+1))==T)
return mid;
if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
return mid-1;
if((mid*(mid+1))>T)
h=mid-1;
else
l=mid+1;
}
return 0;
}
【问题讨论】:
-
您的问题是,当您以 92761 开头时,mid*(mid+1) 将大于最大可能整数并变为负值。改为 long 而不是 int。
-
在楼梯上,A = h(h+1)/2,所以 h^2 + h =2A。求解得到 h = (sqrt(8A+1)-1)/2。不需要循环。
-
@MattTimmermans 您应该将其发布为答案。
-
如果你想用二分搜索来解决这个问题,你可以从你的下限开始加快速度,等于
sqrt(A)。但一个更好的解决方案是 Matt Timmermans 在他的评论中提出的。我在答案中添加了一些细节。
标签: java data-structures binary-search