zoukankan      html  css  js  c++  java
  • Leetcode 69. Sqrt(x)

    69. Sqrt(x)

    Total Accepted: 99997 Total Submissions: 388728 Difficulty: Medium

    Implement int sqrt(int x).

    Compute and return the square root of x.

    思路:可以直接用sqrt函数。但实际上这题考察的是二分查找,二分查找实际比较容易写错。最终返回的是左边最靠近x平方根的数,考虑左闭右开

    代码:
    最简单的方法:

    1 class Solution {
    2 public:
    3     int mySqrt(int x) {//1579205274
    4         int half=(int)sqrt(x);
    5         return half;
    6     }
    7 };

    二分查找:左闭右开:left有效,right无效。

    形式一:

     1 class Solution {
     2 public:
     3     int mySqrt(int x) {
     4         int left=0,right=x;
     5         while(left<right){
     6             int mid = right - (right-left)/2;
     7             if(mid<=x/mid) left=mid;
     8             else{
     9                 right=mid-1;
    10             }
    11         }
    12         return left;
    13     }
    14 };

    形式二:

     1 class Solution {
     2 public:
     3     int mySqrt(int x) {//1579205274
     4         if(x<=1){
     5             return x;
     6         }
     7         //左闭右开,所以初始化时,right>left
     8         int mid,left=1,right=x;
     9         while(left<right){
    10             mid=left+(right-left)/2; //写成(right+left)/2,会造成溢出
    11             if(x/mid>=mid){
    12                 left=mid+1;
    13             }
    14             else{
    15                 right=mid;
    16             }
    17         }
    18         return left-1;
    19     }
    20 };
  • 相关阅读:
    XXX is not in the sudoers file
    git错误“无法推送一些引用到xxx"的解决方法
    mysql开启远程访问
    ubuntu 在启动器中启动webstorm和phpstorm
    ubuntu nginx卸载和安装
    基于grunt构建的前端集成开发环境
    fullPage.js
    常见的HTTP状态码
    JS随机数
    CSS3简单的动画
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5634955.html
Copyright © 2011-2022 走看看