FTPrep, 69 Sqrt(x)

来源:互联网 发布:java 定义object数组 编辑:程序博客网 时间:2024/06/01 08:26
二分法解题,关键就是确定left 和 right,while 条件,和内部的变化。这道题,要有画面感,2条曲线: y=x, y=x*x ,这样在取第一个 right时,就是准确取到 right = x/2 + 1
另外在判断 while 内部的条件时,可以通过考虑1,2这种简单的case来判断有没有等号,因为 mid = (left + right)/2 这是肯定的。
本题的特点:退出条件是 一个区间,更新left和更新right也都是一个区间。一定要完全cover,不能有遗漏也不能有重合。

代码:

class Solution {    public int mySqrt(int x) {        if(x<0) return -1;        if(x==0) return 0;        int left = 1;        // key        int right = x/2+1;   // think about the case: 1, also the curve of y=x*x and y=x, straight line.        while(left<=right){   // think about the case: 1,            int mid= left+(right-left)/2;               if( mid<= x/mid && x/(mid+1)<(mid+1)) return mid;            else{                if(x/(mid+1)>=(mid+1)) left=mid+1;                else right= mid-1; //            }        }        return 0;    }}


原创粉丝点击