leetcode69

simple

This question is the core of dichotomy

Find the dichotomy is as follows:

(1) First, start the search from the middle element of the array, if that element happens to be the target element, the search process ends, otherwise the next step.

(2) If the target element is greater than / less than the intermediate element in the array is greater than / less than half of the intermediate element regions lookup, then repeat the operation in step (1).

(3) If a step in the array is empty, then could not find the target element.

A binary search time complexity of O (logn).
----------------
enter into this problem can have such a transformation.

The square root seeking operation is done. Stupid traversal method is one by one.

But obviously I want to spend a lot of time.

It must be smaller than the square root of a number of one-half of his

Another point

square function of x (x = Y 2 ) is a monotonically increasing function

So the use of binary search can save a lot of time.

class Solution {
    public int mySqrt(int x) {
        if(x<2)return x;
        long num;
        //二分法就是移动边界
       int left=2;//左边界
       int right=x/2;//右边界
       int pricot;//平方根
       while(right>=left){//左右节点不装在一起
           pricot=left+(right-left)/2;
           num=(long)pricot*pricot;//如果数字过大pricot会溢出
           if (num>x) right=pricot-1;//
           else if(num<x) left=pricot+1;
           else return pricot;
       }

       return right;
    }
//测试用例
    public static void main(String[] args) {

        Solution solution = new Solution();
        System.out.println( solution.mySqrt(2147395599));
    }
}

Guess you like

Origin www.cnblogs.com/yanzezhong/p/12561762.html