-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfirst-bad-version.cpp
More file actions
33 lines (27 loc) · 864 Bytes
/
Copy pathfirst-bad-version.cpp
File metadata and controls
33 lines (27 loc) · 864 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* https://leetcode.com/problems/first-bad-version/ */
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int end = n;
int beg = 0;
int mid;
if (n == 1) {
if (isBadVersion(1)) return 1;
else return 0;
}
while (beg <= end) {
mid = beg + (end - beg) / 2;
if (isBadVersion(mid) == 1 && isBadVersion(mid - 1) == 0) return mid;
if (isBadVersion(mid + 1) == 1 && isBadVersion(mid) == 0) return mid + 1;
if (isBadVersion(mid - 1) == 1 && isBadVersion(mid - 2) == 0) return mid - 1;
if (isBadVersion(mid) == 0) {
beg = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
};