Skip to content

Commit 428f340

Browse files
Create Day 1 First Bad Version.cpp
1 parent 754e114 commit 428f340

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Day 1 First Bad Version.cpp

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
PROBLEM:
2+
3+
4+
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product
5+
fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
6+
7+
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.
8+
9+
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad
10+
version. You should minimize the number of calls to the API.
11+
12+
Example:
13+
14+
Given n = 5, and version = 4 is the first bad version.
15+
16+
call isBadVersion(3) -> false
17+
call isBadVersion(5) -> true
18+
call isBadVersion(4) -> true
19+
20+
Then 4 is the first bad version.
21+
22+
23+
SOLUTION:
24+
25+
26+
// The API isBadVersion is defined for you.
27+
// bool isBadVersion(int version);
28+
29+
class Solution {
30+
public:
31+
int firstBadVersion(int n) {
32+
int ans,l,h,m;
33+
l=1;
34+
h=n;
35+
36+
while(l<=h) ////lower bound binary search
37+
{
38+
m=l+(h-l)/2;
39+
40+
if(isBadVersion(m))
41+
{
42+
ans=m;
43+
h=m-1;
44+
}
45+
else
46+
{
47+
l=m+1;
48+
}
49+
}
50+
51+
return ans;
52+
53+
54+
}
55+
};

0 commit comments

Comments
 (0)