【问题标题】:Using an invariant to determine boundary conditions in binary search使用不变量来确定二分搜索中的边界条件
【发布时间】:2020-07-06 01:49:14
【问题描述】:

我正在尝试解决 LeetCode.com 上的Arranging Coins

您总共有 n 个硬币要形成一个阶梯形状,其中每 k 行 必须正好有 k 个硬币。给定 n,找出可以形成的完整楼梯行的总数。 n 是一个非负整数,并且在 32 位有符号整数的范围内。对于 n=5,输出为:2。

基于the solution given,我们可以将问题重新表述为:

找到最大的k 使得k*(k+1)/2<=N

我的不变量(灵感来自this Quora 答案):

我有一个从 L 到 R 的区间,即 a[L]k*(k+1)/2<=N 和 a[R]>k*(k+1)/2&lt;=N。然后,在我检查中间的元素 M 之后,我将 L 或 R 设置为 M,保留不变量。

但我不确定我的不变量是否正确:

  1. 我不确定这是否会给我 k 的 maximum 值;
  2. 我应该继续迭代@​​987654331@ 还是while(l&lt;=r)lr 是通常用于迭代的两个指针;
  3. 在我将mid 计算为k*(k+1)/2 之后,我应该使用l=mid+1 还是l=mid(同样是r=mid-1r=mid)?

谢谢!

【问题讨论】:

  • 公式看不懂有没有质量更好的版本???
  • @YunfeiChen,编辑。谢谢指出!

标签: c++ algorithm binary-search invariants loop-invariant


【解决方案1】:

你把问题弄得太复杂了,从逻辑上讲,你需要做的就是:

int number = n; //the number you are getting
int index = 0;
int iteration = 0;
while(index <= number){
    iteration++;
    index += iteration;
}
return iteration; //this will be the maximum complete level, the code is incomplete but this sounds like an assignment so good luck!!

要获得更有效的解决方案,您可以使用 Guass 的公式来总结数字,例如总结数字 1-100,您可以执行以下操作: 101*100/2 或 (n+1)*n/2.. 因此,如果您觉得舒服,您可以:

int number = n; //the number you are getting
double iteration = sqrt(number/2.0)*2;//remember to add the brackets 
                                      //inside.
if(iteration - Math.floor(iteration) >= 0.5)return iteration + 1;
else return iteration;

如有错误欢迎指正...

【讨论】:

  • 这是O(n)。 :)
  • 总是选择最易读和最简单的解决方案,如果您不需要指针,请不要创建...
  • 此外,我的问题更多是关于不变量 - 而不是如何解决问题本身。
  • 你知道你不喜欢的两个 while 循环比 O(n)....
  • 我给你一个 O(1) 的解决方案,我认为你不能做得更好......
猜你喜欢
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-18
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多