跳至主要內容

69. x 的平方根


69. x 的平方根 open in new window

🟢   🔖  数学 二分查找  🔗 LeetCodeopen in new window

题目

Given a non-negative integer x, return the square root ofx rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Example 1:

Input: x = 4

Output: 2

Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8

Output: 2

Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

Constraints:

  • 0 <= x <= 2^31 - 1

题目大意

给你一个非负整数 x ,计算并返回 x 的 算术平方根 。

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

注意:不允许使用任何内置指数函数和算符,例如 c++ 中的 pow(x, 0.5) 或者 python 中的 x ** 0.5

解题思路

可以通过二分查找得到答案。

  • 二分查找的下界为 0,上界可以粗略地设定为 x
  • 在二分查找的每一步中,只需要比较中间元素 mid 的平方与 x 的大小关系,并通过比较的结果调整上下界的范围。- 由于所有的运算都是整数运算,不会存在误差,因此在得到最终的答案 res 后,也就不需要再去尝试 res+1 了。

复杂度分析

  • 时间复杂度O(logx),即为二分查找需要的次数。
  • 空间复杂度O(1)

代码

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function (x) {
	if (x == 1 || x == 0) return x;
	let left = 0,
		right = x,
		res;
	while (left <= right) {
		let mid = ((left + right) / 2) | 0;
		if (mid * mid > x) {
			right = mid - 1;
		} else {
			res = mid;
			left = mid + 1;
		}
	}
	return res;
};

相关题目

题号标题题解标签难度
50Pow(x, n)open in new window[✓]open in new window递归 数学
367有效的完全平方数open in new window数学 二分查找