278. First Bad Version

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

S: binary search二分答案

    int firstBadVersion(int n) {
        if (n < 1) return 0;
        int start = 1;
        int end = n;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (isBadVersion(mid)) {
                end = mid;
            }
            else {
                start = mid;
            }
        }
        return isBadVersion(start)? start: end;
    }

374. Guess Number Higher or Lower

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example:

n = 10, I pick 6.
Return 6.

S: binary search O(logn)

class Solution {
public:
    int guessNumber(int n) {
        return bsearch(1, n);   
    }

    int bsearch(int start, int end) {
        if (start > end) return 0;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (guess(mid) == 0) return mid;
            else if (guess(mid) == 1) start = mid + 1;
            else end = mid - 1;
        }
        return guess(start) == 0? start : end;
    }
};

results matching ""

    No results matching ""