zoukankan      html  css  js  c++  java
  • LeetCode

    Sqrt(x)

    2013.12.22 04:02

    Implement int sqrt(int x).

    Compute and return the square root of x.

    Solution 1:

      The square root can be calculated using a binary iteration, with an initial interval of [1, x - 1].

      Time complexity is O(log2(x)), space complexity is O(1).

    Accepted code:

     1 // 2WA, 1AC, binary search + long long int
     2 class Solution {
     3 public:
     4     int sqrt(int x) {
     5         // IMPORTANT: Please reset any member data you declared, as
     6         // the same Solution instance will be reused for each test case.
     7         long long int xx = x;
     8         
     9         if(x <= 0){
    10             return 0;
    11         }else if(x < 4){
    12             return 1;
    13         }
    14         
    15         long long int ll, rr, mm;
    16         ll = 1;
    17         rr = xx - 1;
    18         while(rr - ll > 1){
    19             mm = (ll + rr) / 2;
    20             // 1WA here, wrong side of '<'
    21             if(xx < mm * mm){
    22                 rr = mm;
    23             }else{
    24                 ll = mm;
    25             }
    26         }
    27         
    28         // 1WA here, return $ll, not $rr
    29         return ll;
    30     }
    31 };

    Solution 2:

      Actually there is no need to use long long int to avoid integer overflow, since "xx < mm * mm" can be replaced with "x / mm < mm".

      Integer underflow is usually safer than overflow, especially when it converges to 0, that's why we use it for some convenience.

      Time complexity is O(log2(x)), space complexity is O(1).

    Accepted code:

     1 // 1AC, integer overflow can be avoided by using '/' instead of '*'.
     2 class Solution {
     3 public:
     4     int sqrt(int x) {
     5         if(x <= 0){
     6             return 0;
     7         }else if(x < 4){
     8             return 1;
     9         }
    10         
    11         long long int ll, rr, mm;
    12         ll = 1;
    13         rr = x - 1;
    14         while(rr - ll > 1){
    15             mm = (ll + rr) / 2;
    16             if(x / mm < mm){
    17                 rr = mm;
    18             }else{
    19                 ll = mm;
    20             }
    21         }
    22         
    23         return ll;
    24     }
    25 };
  • 相关阅读:
    result set sql server
    [转载]:C#、.Net面试题目及答案
    [转载]:合并两个已排序好的int数组,并排序返回c#实现
    [转载]实际举例C#引用类型和值类型的区别
    mysql 性能优化方案
    oracle 并行原理深入解析及案例精粹
    创建Oracle外部表 External Table
    Oracle 分区表
    MySQL索引类型一览
    MySQL配置文件mysql.ini参数详解、MySQL性能优化
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3485744.html
Copyright © 2011-2022 走看看