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

    牛顿迭代法

    https://blog.csdn.net/hnu2012/article/details/72598038

    https://www.cnblogs.com/liujinhong/p/6014973.html

    //牛顿法
    
    class Solution {
    public:
        int mySqrt(int x) {
            if (x <= 1) 
                return x; 
            double x1 = 0, x2 = 1; 
            while (abs(x1 - x2) > 0.000001) { 
                x1 = x2; 
                x2 = x1 / 2 + (double)x / (2 * x1); 
            }
            return (int)x1;
    
        }
    };
    
    //二分查找法
    
    class Solution {
    public:
        int mySqrt(int x) {
            if (x <= 1) return x;
            int left = 0, right = x;
            while (left < right) {
                int mid = left + (right - left) / 2;
                if (x / mid >= mid) left = mid + 1;
                else right = mid;
            }
            return right - 1;
        }
    };

    重新找了一个方便理解的代码:

    https://www.cnblogs.com/liujinhong/p/6014973.html

    x/2可以缩小搜索的范围,x/2的平方要小于x的条件是0到4之间,你会发现,1、2、3通过这个代码都可以正常运行,所以这个搜索范围是合理的。

    x/mid < mid是为了防止mid*mid导致越界

    如果当前mid的平方大于x,那这个值肯定不是我们想要的值,所以mid-1

    如果当前mid的平方小于等于x,并且mid+1的平方是大于x的,那说明mid这个位置一定是分界线,也就是我们要的值;如果当前mid的平方小于等于x,并且mid+1的平方是小于等于x的,那说明mid这个值一定不是我们想要的值,因为不是分界线

    class Solution {
    public:
        int mySqrt(int x) {
            if(x <= 1)
                return x;
            int start = 1,end = x/2;
            while(start <= end){
                int mid = start + (end - start)/2;
                if(x/mid < mid){
                    end = mid - 1;
                }
                else{
                    if(x/(mid + 1) < (mid + 1))
                        return mid;
                    else
                        start = mid + 1;
                }
            }
            return 0;
        }
    };
  • 相关阅读:
    Azure Active Directory document ---reading notes
    tcp/ip 三次握手和4次挥手
    why microsoft named their cloud service Azure?
    Azure VMs
    Leetcode (C++) 9/20/2017开始
    How do you make an object in C? Used in RTOS.
    HF-DP1: strategy pattern
    确定一下学习的主要参考书
    记一下Thoratec的面试
    《Algorithm in C》by Sedgewick 读书笔记
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/9651043.html
Copyright © 2011-2022 走看看