• [LeetCode#69] Sqrt(x)


    Problem:

    Implement int sqrt(int x).

    Compute and return the square root of x.

    Conclusion for Binary Search Problem:

    Binary search is such an elegant way of solving problems, you must master it!!!
    The problem could use binary search always possess following characteristics. 
    1. we want to find an element in a series? (Kth element, Sqrt root ...)
    2. the series has certain properties, that we can base on one element's info to exclude the elements before or after it. 
        2.1 find certain element e in a sorted array. If nums[mid] < e, we can exclude nums[0] to nums[mid]. 
        2.2 find first bug version. Once a bug version appears, {all versions after it are bug version}. if version[mid] is not a bug version, we can discard way the part from version[0] to version[mid]. 
        ...
        In total, we can base on an element's info, to infer the elements before and after it.
    
    During the search process, we should take care of following things:
    1. overflow problem. it may happen at the place we checking the mid index, and it may happen when we check value.
    2. the mid element may be the answer, you should clearly define the way to update front and end(exclude mid or not). 
    
    The process to use Binary Search.
    Step 1: Ddentify the property, how can we use it?
    Step 2: Design the proper intial search boundary. What are the initial values of front and end? 
    Step 3: Indentify the stop condition.
    Note: the stop condidation may not be a certain point, it could be {a succsive range}. (Where the answer is?) We can use the target to indenify the stop condidation. 

    Problem Analysis:

    The question: search the sqrt of x.
    Target: search an integer m from [0, x], whose value meet:   x<= m^2 and (m+1)^2 > x.
    Step 1: for each integer in [0, x],  if x < y, x^2 < y^2. Thus the series has sorted property, which could used for comparision.
    Step 2: The search boundary is [0, x]. But we can seperate x out.
    Step 3: Based on the tareget. the stop condition is "x/mid >= mid && x/(mid+1) < mid+1".

    Wrong Solution:

    public class Solution {
        public int mySqrt(int x) {
            if (x < 0)
                throw new IllegalArgumentException("x is not allowed in negative!");
            int front = 0;
            int end = x;
            while (front <= end) {
                int mid = front + (end - front) / 2;
                if (mid * mid == x) {
                    return mid;
                } else if (mid * mid > x){
                    end = mid - 1;
                } else {
                    front = mid + 1;
                }
            }
            return front - 1;
        }
    }

    Mistake Analysis:

    Submission Result: Time Limit Exceeded 
    Last executed input:
    2147483647
    
    The above solution has following problems:
    1. Even it try to avoid the overflow when calculate mid index, it incurs overflow when doing:
    mid * mid == x. 
    Note: Always write '*' through '/' and write '+' through '-'.
    2. Wrong stop condition. Since the target meet "mid^2 <= x < (mid+1)^2", it actually covers a succsive range of x. 
    ------------------------------------------------------------------------------------------------------------------
    Fix method for above two problems:
    int mid = front + (end - front) / 2;
    if (x/mid >= mid && x/(mid+1) < mid+1) {
    ...
    }
    Improvement:
    The initial font of sqrt problem could be 
    int end = (x/2 + 1)

    Solution:

    public class Solution {
        public int mySqrt(int x) {
            if (x < 0)
                throw new IllegalArgumentException("x is not allowed in negative!");
            if (x == 0)
                return 0;
            int front = 1;
            int end = x;
            while (front <= end) {
                int mid = front + (end - front) / 2;
                if (x/mid >= mid && x/(mid+1) < mid+1) {
                    return mid;
                } else if (mid > x/mid){
                    end = mid - 1;
                } else {
                    front = mid + 1;
                }
            }
            return 0;
        }
    }
  • 相关阅读:
    四级英语day9
    123
    像程序员一样思考
    Kali
    OS X
    Effective Java
    DHU ACM OJ
    Ambari
    Hadoop
    Hadoop2
  • 原文地址:https://www.cnblogs.com/airwindow/p/4793920.html
Copyright © 2020-2023  润新知