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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,906评论 0 38
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,969评论 19 139
  • 依赖注入(Dependency Injection) 今天我们讨论的内容核心是面向接口编程,我决定还是要从依赖注入...
    zhiyi阅读 14,133评论 8 79
  • 各位中银国际的洛卡的家人们,大家晚上好。很荣幸又经济又担任今天晚上的分享主持。可能在我们这个群熟悉杨开琴总代的人肯...
    李玉婷_57ad阅读 461评论 0 0