[LeetCode-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.

  • 分析

样例

给出 n=5

调用isBadVersion(3),得到false

调用isBadVersion(5),得到true

调用isBadVersion(4),得到true

此时我们可以断定4是第一个错误的版本号

第一段代码:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

int firstBadVersion(int n) 
{	
	if(n <= 0)
		return 0;
	int low = 1;
	int high = n;
	int mid;
	bool value;
	while(low <= high) {
		mid = (low+high)/2;
		value = isBadVersion(mid);
		if(value) { 	/*为真发现错误版本*/
			high = mid - 1;
		}
		else {
			low = mid + 1;
		}
			
	}
	return low;
}

[LeetCode-278] First Bad Version(二分法注意事项)_第1张图片

说明数据发生了溢出,mid = (low+high)先发生了数据溢出,应该将其改为mid = low+(high-low)/2;

bool isBadVersion(int version);

int firstBadVersion(int n) 
{	
	if(n <= 0)
		return 0;
	int low = 1;
	int high = n;
	int mid;
	bool value;
	while(low <= high) {
		mid = low+(high-low)/2;
		value = isBadVersion(mid);
		if(value) { 	/*为真发现错误版本*/
			high = mid - 1;
		}
		else {
			low = mid + 1;
		}
			
	}
	return low;
}


你可能感兴趣的:(LeetCode,二分法)