Create 278. First Bad Version.md

This commit is contained in:
唐树森 2018-10-10 20:56:48 +08:00 committed by GitHub
parent 2b253b48e0
commit 5525899477
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

24
278. First Bad Version.md Normal file
View File

@ -0,0 +1,24 @@
# [278. First Bad Version](https://leetcode.com/problems/first-bad-version/description/)
# 思路
思路很简单,就是二分法。
但是这题会超时,其实问题不是时间复杂度高(二分法的时间复杂度已经是理论最低了),而是因为在计算`mid = (low + high) / 2`时low + high会溢出而产生不可预料的值。
所以,我们不应该用`mid = (high + low) / 2`来更新mid而应该`mid = low + (high - low) / 2`。
> **以后的二分法都应该这样更新mid以防溢出**
# C++
```
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int low = 1, high = n, mid;
while(low <= high){
mid = low + (high - low) / 2; // mid = (high + low) / 2 会溢出!!!
if(isBadVersion(mid)) high = mid - 1;
else low = mid + 1;
}
return low;
}
};
```