程序媛詹妮弗
终身学习

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.

Given n = 5

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version. 

 

题意:

 

思路:

二分查找。 

注意的是,每个人的二分查找模板可能都不同。

源于对left和right的初始化不同。一旦定义好了left和right的区间,就要在之后的代码里维护好这个区间。

举例,

 

定义好left = 0, right = n-1, 则在[left...right] 范围内找target,极端情况下left会一直靠向right直至等于right。 

 1   private int binarySearch2(int n, int[]arr, int target){
 2         int l = 0, r = n-1 ;
 3         while(l <= r){
 4             int mid = l+(r-l)/2;
 5             if(arr[mid] == target){
 6                 return mid;
 7             }else if(target > arr[mid]){
 8                 l = mid + 1;
 9             }else {
10                 r = mid-1 ;
11             }
12         }
13         return -1;
14     }

定义好left = 0, right = n, 则在 [left...right) 范围内找target,极端情况下left会一直靠向right但不能等于right。 

 1    private int binarySearch(int n, int[]arr, int target){
 2         int l = 0, r = n ;
 3         while(l < r){
 4             int mid = l+(r-l)/2;
 5             if(arr[mid] == target){
 6                 return mid;
 7             }else if(target > arr[mid]){
 8                 l = mid + 1;
 9             }else {
10                 r = mid ;
11             }
12         }
13         return -1;
14     }

 

当然, 与此相对应的,也可以初始化 left = -1, 思路一致。 选择一套自己好理解的模板,白子偕老。

 

代码:

 1 public class FirstBadVersion {
 2     public int firstBadVersion(int n) {
 3         int left = 1, right = n - 1;
 4         while (left <= right) {
 5             int mid = left + (right - left) / 2;
 6             if (!isBadVersion(mid)) {
 7                 left = mid + 1;
 8             } else {
 9                 right = mid - 1;
10             }
11         }
12         return left;
13     }
14 }

 

posted on 2018-06-05 07:09  程序媛詹妮弗  阅读(170)  评论(0编辑  收藏  举报