69. Sqrt(x)

Description

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

Solution

Binary search, time O(logn), space O(1)

用二分解就可以了,注意二分判断的条件
if (mid < x / mid)
这里一定要保证mid > 0,否则会抛Runtime Exception,这就要求对x < 2进行预处理。

也可以用一个long square = (long) mid * mid,然后用square和x作比较来二分,也比较简单。

注意如果x不是perfect square,需要返回right而非left!

class Solution {
    public int mySqrt(int x) {
        if (x < 0) {
            return -1;
        }
        
        if (x < 2) {
            return x;
        }
        
        int left = 0;
        int right = x;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (mid < x / mid) {    // ensure mid > 0!
                left = mid + 1;
            } else if (mid > x / mid) {
                right = mid - 1;
            } else {
                return mid; // x is perfect square
            }
        }
        
        return right;   // x is not a perfect square, round down
    }
}

或者用long表示pow也可以,写起来更方便:

class Solution {
    public int mySqrt(int x) {
        int left = 0;
        int right = x;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            long pow = (long) mid * mid;

            if (pow > x) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        
        return right;
    }
}

你可能感兴趣的:(69. Sqrt(x))