LeetCode_278. First Bad Version
2024-08-26 21:29:14
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;
}
}
}
最新文章
- css3-新属性-用户界面
- ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn&#39;t supported yet
- Android——使用SQLiteDatabase操作SQLite数据库
- sitemesh学习笔记(3)
- Object C语法学习
- paper 49:论文退稿?审稿人帮你总结了22个能避免的常见问题
- Build AssetBundle, missing shader.
- System.Management命名空间
- C实现单链表
- scrapy框架修改单个爬虫的配置,包括下载延时,下载超时设置
- react 环境搭建
- 如何在Vue中建立全局引用或者全局命令
- innodb_flush_log_at_trx_commit
- javax.persistence.RollbackException: Error while committing the transaction
- slf4j使用
- mysqlslap
- [Z] Shell中脚本变量和函数变量的作用域
- TOEFL考试(一年半的复仇,裸考)
- XmlAutoGo
- java: jdk1.8以后就不支持桥接的方式
热门文章
- python - django (创建到运行流程)
- 【贪心】Moving Tables POJ 1083
- netty: 以默认的ByteBuf作为传输数据
- C# 接收C++ dll 可变长字节或者 字符指针 char*
- webuploader+php如何实现分片+断点续传
- 删除tppabs,href=";javascript:if(confirm)...";,、/*tpa=http://...
- 洛谷 P1257 平面上的最接近点对 题解
- php-fpm nginx 超时参数设置
- 使用Android的日志工具Log
- 数据结构Java版之遍历二叉树(六)