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;
        }
    }
  • 相关阅读:
    BFS(从数字A变到数字B每次只能换一个数)
    BFS(数字a通过三种操作到数字B)
    dfs+bfs(三种路径问题)
    国际象棋跳马问题
    拓扑排序
    hadoop-hdfs、mapreduce学习随笔
    hive初探2_数据模型
    hive初探_框架组成、简单使用
    Scala学习笔记
    Scala安装
  • 原文地址:https://www.cnblogs.com/airwindow/p/4204966.html
Copyright © 2011-2022 走看看