Skip to content

Commit 52dbd39

Browse files
committed
chore(easy): add First Bad Version
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
1 parent 663b32a commit 52dbd39

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

easy/first-bad-version/README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# 278. First Bad Version
2+
3+
See: [First Bad Version](https://leetcode.com/problems/first-bad-version/).
4+
5+
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.
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 version. You should minimize the number of calls to the API.
10+
11+
Example:
12+
13+
```sh
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+
```

easy/first-bad-version/solution.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Forward declaration of isBadVersion API.
3+
* @param version your guess about first bad version
4+
* @return true if current version is bad
5+
* false if current version is good
6+
* func isBadVersion(version int) bool;
7+
*/
8+
9+
func search(start, end int) int {
10+
half := int((end - start)/2) + start
11+
if !isBadVersion(half) {
12+
return search(half+1, end)
13+
}
14+
15+
if isBadVersion(half-1) {
16+
return search(start, half)
17+
}
18+
19+
return half
20+
21+
}
22+
23+
func firstBadVersion(n int) int {
24+
return search(1, n+1)
25+
}

0 commit comments

Comments
 (0)