【问题标题】:Binary Search, when should I increment high or low?二进制搜索,我应该何时增加高或低?
【发布时间】:2016-10-21 05:41:30
【问题描述】:

我很难理解如何增加低或高。

例如,这是一个来自 leetcode 的问题:

实现 int sqrt(int x)。

我的代码:

class Solution {
public:
    int mySqrt(int x) {
        if (x<=0) return 0;
        int low=1, high=x, mid=0; 
        while (low<=high){          // should I do low<high?
            mid=low+(high-low)/2;
            if (x/mid==mid) return mid; 
            if (x/mid>mid) low= mid+1;  //can I just do low=mid?
            else           high=mid-1; // can I do high =mid?

        }
        return high;  //after breaking the loop, should I return high or low?

    }
};

你看,一个条件满足后,我不知道该设置low=mid还是low=mid+1。为什么是mid+1

一般来说,我很难确定是否应该从中点低点增加。我什么时候应该在while 循环中包含low &lt;= highlow &lt; high 也遇到了麻烦。

【问题讨论】:

  • if (x/mid==mid) 返回中值;在这里,您检查 mid 作为平方根,如果是,则从这里返回。所以我们倾向于不再检查它。所以我们做低=中+1和高=中-1
  • 而且通过这种方法,除了少数情况,您不会得到任何数字的平方根。
  • 阅读这里。希望这将消除您的所有疑虑。 geeksforgeeks.org/square-root-of-a-perfect-square

标签: binary-search


【解决方案1】:

您的算法不是二分搜索。 而且,它也不起作用。

以 x = 5 为例

Initial:
low = 1, high = 5

Iter 1:
mid = 3
5/3 = 1 so high = 4

Iter 2:
mid = 2.5 => 2 (because int)
5/2 = 2 (because int)

<returns 2>

对于完美的正方形输入,您的算法只能通过mid 而不是highlow 给出正确的结果。

顺便说一句,如果x/mid &gt; mid,你需要增加mid,否则你需要减少它。您增加和减少mid 的方法分别是增加low 或减少high

这没问题,但这不会产生二分搜索。您的high 将遍历从x(2*sqrt - 1) 的所有整数。

请关注@sinsuren 评论以获得更好的解决方案

【讨论】:

    【解决方案2】:

    这是Babylonian求平方根的方法:

    /*Returns the square root of n.*/
    float squareRoot(float n)
    {
      /*We are using n itself as initial approximation
       This can definitely be improved */
      float x = n;
      float y = 1;
      float e = 0.000001; /* e decides the accuracy level*/
      while(x - y > e)
      {
        x = (x + y)/2;
        y = n/x;
      }
      return x;
    }
    

    想了解更多,可以关注this link

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2014-07-10
      • 2014-03-22
      • 1970-01-01
      相关资源
      最近更新 更多