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;
        }
    }
  • 相关阅读:
    纯JS.CSS编写的可拖拽并左右分栏的插件(复制代码就能用)
    jquery on()方法重复绑定解决方法
    在PHP语言中使用JSON和将json还原成数组
    Flex 布局教程:语法篇
    在线生成大全(这里真的什么都有)
    css3(border-radius)边框圆角详解
    css常用鼠标指针形状代码
    input 正则限制输入内容
    html中input标签的tabindex属性
    CSS gradient渐变之webkit核心浏览器下的使用
  • 原文地址:https://www.cnblogs.com/airwindow/p/4204966.html
Copyright © 2011-2022 走看看