LeetCode 278.

Tags:

Intuition

Binary Seaching to find the answer

Approach

Binary Seaching

Complexity

  • Time complexity: O(logn)

  • Space complexity: O(1)

Code

class Solution {
    public int firstBadVersion(int n) {
        int left = 1, right = n, mid = left + (right - left) / 2;
        while (left <= right) {
            if (left == right) return left;
            mid = left + (right - left) / 2;
            if (isBadVersion(mid)) {
                right = mid;
            }else{
                left = mid + 1;
            }
        }
        return mid;
    }
}

Check out the description of this problem at LC 278.