278. First Bad Version

Easy

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.

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true Then 4 is the first bad version.
package leetcode.easy;
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */ public class FirstBadVersion extends VersionControl {
public int firstBadVersion1(int n) {
for (int i = 1; i < n; i++) {
if (isBadVersion(i)) {
return i;
}
}
return n;
} public int firstBadVersion2(int n) {
int left = 1;
int right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
} @org.junit.Test
public void test() {
FirstBadVersion firstBadVersion = new FirstBadVersion();
System.out.println(firstBadVersion.firstBadVersion1(5));
System.out.println(firstBadVersion.firstBadVersion2(5));
}
} class VersionControl {
boolean isBadVersion(int version) {
if (version >= 4) {
return true;
} else {
return false;
}
}
}

最新文章

  1. css3-新属性-用户界面
  2. ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn&#39;t supported yet
  3. Android——使用SQLiteDatabase操作SQLite数据库
  4. sitemesh学习笔记(3)
  5. Object C语法学习
  6. paper 49:论文退稿?审稿人帮你总结了22个能避免的常见问题
  7. Build AssetBundle, missing shader.
  8. System.Management命名空间
  9. C实现单链表
  10. scrapy框架修改单个爬虫的配置,包括下载延时,下载超时设置
  11. react 环境搭建
  12. 如何在Vue中建立全局引用或者全局命令
  13. innodb_flush_log_at_trx_commit
  14. javax.persistence.RollbackException: Error while committing the transaction
  15. slf4j使用
  16. mysqlslap
  17. [Z] Shell中脚本变量和函数变量的作用域
  18. TOEFL考试(一年半的复仇,裸考)
  19. XmlAutoGo
  20. java: jdk1.8以后就不支持桥接的方式

热门文章

  1. python - django (创建到运行流程)
  2. 【贪心】Moving Tables POJ 1083
  3. netty: 以默认的ByteBuf作为传输数据
  4. C# 接收C++ dll 可变长字节或者 字符指针 char*
  5. webuploader+php如何实现分片+断点续传
  6. 删除tppabs,href=&quot;javascript:if(confirm)...&quot;,、/*tpa=http://...
  7. 洛谷 P1257 平面上的最接近点对 题解
  8. php-fpm nginx 超时参数设置
  9. 使用Android的日志工具Log
  10. 数据结构Java版之遍历二叉树(六)