Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

x 的平方根-69 #24

Open
sl1673495 opened this issue May 9, 2020 · 1 comment
Open

x 的平方根-69 #24

sl1673495 opened this issue May 9, 2020 · 1 comment
Labels
二分查找 复习 * 1 复习了一遍的题目

Comments

@sl1673495
Copy link
Owner

  1. x 的平方根

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 x 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

输入: 4
输出: 2

示例 2:

输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。

思路

本题利用二分查找来求解,一开始把右边界粗略的设定为目标值 x,左右边界的中间值设为 mid,然后在二分过程中每次发现 mid * mid < x 的情况,就把这个 mid 值记录为 ans。

如果计算出的乘积正好等于 x,就直接返回这个 mid 值。

如果二分查找超出边界了,无论最后的边界是停留在小于 x 的位置还是大于 x 的位置,都返回 ans 即可,因为它是最后一个乘积小于 x 的值,一定是正确答案。

/**
 * @param {number} x
 * @return {number}
 */
let mySqrt = function (x) {
  let left = 0;
  let right = x;

  let ans = -1;
  while (left <= right) {
    let mid = Math.round((left + right) / 2);
    let product = mid * mid;
    if (product <= x) {
      ans = mid;
      left = mid + 1;
    } else if (product > x) {
      right = mid - 1;
    } else {
      return mid;
    }
  }

  return ans;
};
@sl1673495 sl1673495 added 二分查找 复习 * 1 复习了一遍的题目 labels May 9, 2020
@vortesnail
Copy link

else { return mid } 这段代码应该是没用的吧😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
二分查找 复习 * 1 复习了一遍的题目
Projects
None yet
Development

No branches or pull requests

2 participants