(medium)LeetCode 278.First Bad Version
2015-09-09 16:07
190 查看
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
You are given an API
方法思想:二分查找,注意红色代码,作用是防止越界
代码如下:
运行结果如下:
Suppose you have
nversions
[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
versionis bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
方法思想:二分查找,注意红色代码,作用是防止越界
代码如下:
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { if(isBadVersion(1)) return 1; int left = 1; int right = n; int mid=0; while(left <= right) { mid = left+(right-left) / 2; if(isBadVersion(mid)) { if(!isBadVersion(mid-1)) return mid; else right=mid-1; } else { left = mid + 1; } } return -1; } }
运行结果如下:
相关文章推荐
- 【iOS】iOS 调试快速定位程序在哪崩溃
- [C++] C++中的构造函数和析构函数的显式调用
- linux系统开机流程以及grub的配置
- 临时表空间过大,重建临时表空间
- apache StopWatch基本使用
- Intellij 在使用过程中遇到的问题及解决方法
- eclipse的debug的单点调试
- win7 64位配置mysql 5.6免安装版
- 杂记
- C#打印螺旋数组
- Egret note
- 用JS判断IE版本的代码
- linux 下查看网速的方法 (不需要安装任何软件)
- svn系列之一服务端下载和安装
- socket编程之select()
- Visual Foxpro 6.0 中文版安装向导(图解)
- 执行maven-build.cmd失败
- Java泛型详解二
- python列表和元组
- 颜色空间总结