I understand that for binary search

dichotomy

For the interval [a, b] continuous and f (a) · f (b ) < 0 the function y = f (x), by continuous zeros interval where the function f (x) is divided into two, that the two end sections gradually approaching zero , zero and thus give an approximation method is called dichotomy.

This is the dichotomy in contact with my high school, most began to feel this method seconds ah! But after a long time will remember what is not, wait until they start to learn to use the computer algorithm to find the binary search frequency is a bit high, so I want to sum up the binary search.

Direct that title by title conclusions:

leetcode 69 questions:

Achieve int sqrt (int x) function.

Computes and returns the square root of x, where x is a non-negative integer.

Since the return type is an integer, the integer part of the result to retain only the fractional part is rounded down.

 

First, I thought the beginning, traversing from 0 to x / 2, because it must be less than equal to the square root of x / 2, so I started knocking the code, then I tangled for a long time in these nodes above 1,0,2 , but then I did not find the right, then I want to do with the stack, at the time of traversal if i * i <= x to push, if more than returns the top element. Later I found out this way, not only does not change the time complexity, space complexity is also larger. Read the solution to a problem is discovered binary search, seconds later only to find really carefully read ah!

1  class Solution {
 2      public  int mySqrt ( int X) {
 . 3          Long left = 0 ;
 . 4          Long right = (X >>> 1) + 1'd ; // I is blinded deceives the >>> 1, each have forgotten the significance of this bit operations
 . 5          the while (left < right) {
 . 6              Long MID = (left + right +. 1) / 2 ;
 . 7              Long NUM = MID * MID;
 . 8              IF (NUM> X) {
 . 9                  right = MID -. 1 ;
 10              } the else {
 . 11                  left = mid;
12             }
13         }
14         return (int)left;
15     }
16 }

I think the most important thing is to find half of the border looking for, find the right boundary will find a shortcut.

 

Guess you like

Origin www.cnblogs.com/frank9571/p/11988579.html