[LintCode] First Bad Version

http://lintcode.com/en/problem/first-bad-version/

/**
 * public class VersionControl {
 *     public static boolean isBadVersion(int k);
 * }
 * you can use VersionControl.isBadVersion(k) to judge wether 
 * the kth code version is bad or not.
*/
class Solution {
    /**
     * @param n: An integers.
     * @return: An integer which is the first bad version.
     */
    public int findFirstBadVersion(int n) {
        // write your code here
        
        int low = 1;
        int high = n;
        
        while (low < high)
        {
            int mid = low + (high - low) / 2;
            
            if (VersionControl.isBadVersion(mid))
            {
                high = mid;
            }
            else
            {
                low = mid + 1;
            }
        }
        
        if (VersionControl.isBadVersion(low))
            return low;
        else
            return -1; // Not found.
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章