278. First Bad Version
278. First Bad Version
初雪之音 发表于12个月前
278. First Bad Version
  • 发表于 12个月前
  • 阅读 40
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

Description

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.

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.

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.

原题

代码库的版本号是从 1 到 n 的整数。某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错。请找出第一个错误的版本号。
你可以通过 isBadVersion 的接口来判断版本号 version 是否在单元测试中出错,具体接口详情和调用方法请见代码的注释部分。

给出 n=5
调用isBadVersion(3),得到false
调用isBadVersion(5),得到true
调用isBadVersion(4),得到true
此时我们可以断定4是第一个错误的版本号

解题思路

  • 相当于找第一个target元素,例如找第一个1
    00000001111111111111111

代码

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int result = 0;

		if (n > 0) {
			int left = 0, right = n;
			while (left + 1 < right) {
				int mid = left + (right - left) / 2;
				if (isBadVersion(mid)) {
					right = mid;
				} else {
					left = mid;
				}
			}
			if (isBadVersion(right)) {
				result = right;
			} else {
				result = left;
			}
		}

		return result;
    }
}

 

标签: leetcode
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 39
博文 238
码字总数 134896
×
初雪之音
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: