本文主要是介绍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.
分析:
一开始错在把mid=(high+low)/2,直接这样写了。需要考虑high+low>=2^31的问题。
代码:
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);class Solution {
public:int firstBadVersion(int n) {if(isBadVersion(1))return 1;int low=1,high=n;while(low<high){int mid;if(low%2&&high%2)mid=low/2+high/2+1;else mid=low/2+high/2;if(isBadVersion(mid))high=mid;else low=mid+1;}return low;}
};
这篇关于LeetCode *** 278. First Bad Version的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!