Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0a2aaff

Browse files
committed
commit solution 278
1 parent a167b5b commit 0a2aaff

File tree

3 files changed

+105
-0
lines changed

3 files changed

+105
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# [278. 第一个错误的版本](https://leetcode-cn.com/problems/first-bad-version/description/)
2+
3+
### 题目描述
4+
5+
<p>你是产品经理,目前正在带领一个团队开发新的产品。不幸的是,你的产品的最新版本没有通过质量检测。由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本都是错的。</p>
6+
7+
<p>假设你有 <code>n</code> 个版本 <code>[1, 2, ..., n]</code>,你想找出导致之后所有版本出错的第一个错误的版本。</p>
8+
9+
<p>你可以通过调用&nbsp;<code>bool isBadVersion(version)</code>&nbsp;接口来判断版本号 <code>version</code> 是否在单元测试中出错。实现一个函数来查找第一个错误的版本。你应该尽量减少对调用 API 的次数。</p>
10+
11+
<p><strong>示例:</strong></p>
12+
13+
<pre>给定 n = 5,并且 version = 4 是第一个错误的版本。
14+
15+
<code>调用 isBadVersion(3) -&gt; false
16+
调用 isBadVersion(5)&nbsp;-&gt; true
17+
调用 isBadVersion(4)&nbsp;-&gt; true
18+
19+
所以,4 是第一个错误的版本。&nbsp;</code></pre>
20+
21+
### 解题思路
22+
23+
1. 二分查找
24+
25+
### 具体解法
26+
27+
28+
#### **Golang**
29+
```go
30+
func firstBadVersion(n int) int {
31+
l, r := 1, n
32+
for l < r {
33+
mid := (l + r) / 2
34+
if isBadVersion(mid) {
35+
r = mid
36+
} else {
37+
l = mid + 1
38+
}
39+
}
40+
return l
41+
}
42+
43+
func isBadVersion(n int) bool {
44+
if n >= 4 {
45+
return true
46+
}
47+
return false
48+
}
49+
```
50+
51+
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package leetcode
2+
3+
/*
4+
* @lc app=leetcode.cn id=278 lang=golang
5+
*
6+
* [278] 第一个错误的版本
7+
*/
8+
9+
// @lc code=start
10+
/**
11+
* Forward declaration of isBadVersion API.
12+
* @param version your guess about first bad version
13+
* @return true if current version is bad
14+
* false if current version is good
15+
* func isBadVersion(version int) bool;
16+
*/
17+
18+
func firstBadVersion(n int) int {
19+
l, r := 1, n
20+
for l < r {
21+
mid := (l + r) / 2
22+
if isBadVersion(mid) {
23+
r = mid
24+
} else {
25+
l = mid + 1
26+
}
27+
}
28+
return l
29+
}
30+
31+
func isBadVersion(n int) bool {
32+
if n >= 4 {
33+
return true
34+
}
35+
return false
36+
}
37+
38+
// @lc code=end
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package leetcode
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestFirstBadVersion(t *testing.T) {
8+
var ret int
9+
var num int
10+
11+
num = 5
12+
ret = 4
13+
if ret != firstBadVersion(num) {
14+
t.Fatalf("case fails %v\n", ret)
15+
}
16+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /