zoukankan      html  css  js  c++  java
  • 69. Sqrt(x) 求根号再取整

    [抄题]:

    Implement int sqrt(int x).

    Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

    Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

    Example 1:

    Input: 4
    Output: 2
    

    Example 2:

    Input: 8
    Output: 2
    Explanation: The square root of 8 is 2.82842..., and since 
                 the decimal part is truncated, 2 is returned.

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    不知道和二分法有何关系:

    找到第一个/最后一个满足某个条件的位置/值,此乃二分法第二重境界

    [一句话思路]:

    套模板

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 有小数时定义为long

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    1. 有小数时定义为long型

    [复杂度]:Time complexity: O(lgn) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    找到第一个/最后一个满足某个条件的位置/值,此乃二分法第二重境界

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int mySqrt(int x) {
            //bs
            long start = 1, end = x;
            while (start + 1 < end) {
                long mid = start + (end - start) / 2;
                if (mid * mid <= x) {
                    start = mid;
                }else {
                    end = mid;
                }
            }
            
            //return end or start
            if (end * end <= x) {
                return (int)end;
            }
            return (int)start;
    }
    }
    View Code
  • 相关阅读:
    工作流数据结构
    CssFrindly使用
    .NET平台BPM
    关于SQL SERVER高并发访问的解决办法
    Asp.net防止后退(清除页面缓存)
    Attaching the Script debugger to process ‘[****]’ on machine **** failed.
    FlowWork学习(数据库部分)
    SQL Server 存储过程
    AjaxControlToolkit的安装与使用详解
    Cantor定理的一种好表述
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8964816.html
Copyright © 2011-2022 走看看