Using binary search accepted,but there is a question.


  • 0
    U

    class Solution {
    public:
    int mySqrt(int x) {
    if(x == 0 || x == 1) return x;
    int l = 1;
    int r = x;
    //int mid = (l + r)/2;
    int mid;
    int ans = -2;
    while(l <= r){
    mid = l + (r-l)/2;
    if(mid == x/(mid)) return mid;
    else if(mid < (x/mid)) {
    if((mid+1)>(x/(mid+1))) return mid;
    l = mid+1;
    ans = mid;
    }
    else r = mid-1;

        }
        return ans;
    }
    

    };

    It was accept.But when I put the "mid=l + (r-l)/2" behind "r = mid-1" and calculate the first mid out of the loop by "mid = (1+x)/2" ,it was Time Limit Exceeded.So what's the problem .


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.