C++ binary search


  • 0
    X
    // Forward declaration of isBadVersion API.
    bool isBadVersion(int version);
    
    class Solution {
    public:
        int firstBadVersion(int n) {
            //using bibary search
            int l = 1, r = n;
            int ans = -1;
            while(l <= r){
                int mid = l + (r - l) / 2;
                if(isBadVersion(mid)){
                    ans = mid;
                    r = mid - 1;
                }else{
                    l = mid + 1;
                }
            }
            return ans;
        }
    };

Log in to reply
 

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