zoukankan      html  css  js  c++  java
  • [LeetCode#69] Sqrt(x)

    The problem:

    Implement int sqrt(int x).

    Compute and return the square root of x.

    My analysis:

    The problem could be solved amazingly by using binary search.
    When using the algorithm, we should be very careful in in tackling range issues.

    The following skills should be kept in mind.
    1. All binary search has low pointer and high pointer, the terminating condition should be low < = high (index).

    2. Unlike the problem of search in array, whose low and high pointer's initial location could be easily indetified as 0 to length - 1. In this case, the low pointer should start from "1", and the high pointer should start from "x/2 + 1"(this is a little tricky skill). (x/2 + 1) ^ 2 > x. (thus we can guarantee the answer for x in the range)

    3. Since we need to check if a value is the sqrt of a target, we may rushly use mid * mid <= x (very dangerous!!!, the multiplication might lead to overflow)
    if (mid * mid <= x && (mid + 1) * (mid + 1) > x)
    Nicely, this could be sovled by following way: (no need to introduce complex max_value or min_value)
    if (mid < = x / mid && (mid + 1) > x / (mid + 1))
    we could use x directly as bound, the bound is in the range of [1, Max.value]
    (we have already known the bound, unlike the situation in conversion, which we don't know the bound).

    My solution:

    public class Solution {
        public int sqrt(int x) {
            if (x < 0)
                return -1;
                
            if (x == 0)
                return 0; 
    
            int low = 1; // the low should be set to 1. it's different from the search in array.
            int high = x / 2 + 1; // the high should be set to x / 2 + 1
            int mid;
            
            while (low <= high) {
                
                mid = (high + low)/ 2;
                
                if ((x / mid >= mid) && ((mid + 1) > x / (mid + 1))) { //to avoid overflow
                    return mid; 
                } else if ( x / mid < mid ) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
                
            }
            
            return -1;
        }
    }
  • 相关阅读:
    SpringMVC:拦截器拦截时机和原理
    SpringBoot:MessageConverter自动配置原理
    SpringMVC:返回值处理器原理和MessageConverter原理
    SpringMVC:自定义Converter
    XML-RPC协议学习
    ContentControl 与 ViewModel (一)
    C# 获取相对路径(绝对路径转相对路径)
    WPF 最简单的TextBox水印
    WPF/Silverlight开发的15个最佳实践(转发)
    WPF 打印崩溃问题( 异常:Illegal characters in path/路径中有非法字符)
  • 原文地址:https://www.cnblogs.com/airwindow/p/4204966.html
Copyright © 2011-2022 走看看