LeetCode -- 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.
在從1到n的版本號中,找到第1個壞版本,已知如果第i個版本為壞版本,那麼從i+1到n的版本都是壞版本。
思路:
又是一道二分查找題目,應用二分查找思路加入一些特殊邏輯處理即可:
1. 如果當前版本是壞版本:
1.1 上一個版本不是壞版本,返回當前版本
1.2 否則,向左找
2. 如果當前版本不是壞版本:
2.1 下一個版本為壞版本,返回下一個版本
2.2 否則,向右找
最後分別判斷左右版本是否則壞版本即可。
注意中間索引m需要寫成:
var m = (int)(l/2.0 + r/2.0);
這樣做是防止一些大數字加運算越界。
實現代碼:
/* The isBadVersion API is defined in the parent class VersionControl.
bool IsBadVersion(int version); */
public class Solution : VersionControl {
public int FirstBadVersion(int n)
{
var l = 0;
var r = n;
while(l < r - 1){
var m = (int)(l/2.0 + r/2.0);
var mBad = IsBadVersion(m);
if(mBad)
{
if(!IsBadVersion(m-1)){
return m;
}
else{
r = m;
}
}
else{
if(IsBadVersion(m+1)){
return m+1;
}
else{
l = m;
}
}
}
var leftBad = IsBadVersion(l);
var rightBad = IsBadVersion(r);
if(leftBad){
return l;
}
else if(!leftBad && rightBad){
return r;
}
return -1;
}
}