278. First Bad Version java

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.

题意:你是一个产品经理,近期带着你的团队开发一种新产品,不幸的是,你的产品最终的版本因为质检失败你了,因为每个版本都是在上一个版本基础上修改的,所以当某一个版本是坏掉的时候,后面的版本都是坏掉的。

假设:你有n个版本[1,2,...,n]并且你想找出来第一个坏掉的版本,导致弃权后面的版本都坏掉了。

你有一个API, bool isBadVersion(version) 可以用来判断版本否坏掉了,请写一个函数找到第一个坏的版本,你应该尽可能少的调用API函数。

思路:利用二分法找到第一个坏掉的版本!如果找到的是坏版本,就继续往左缩小范围,如果找到的不是坏版本,那么下一个是坏版本的时候,就是第一个坏版本被找到的时候!

java代码:

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left=1;
	int right=n;
        while(left<right)//找到第一个坏掉的版本
        {
        	int number=left+(right-left)/2;
        	if(!isBadVersion(number))//不是坏版本的话,选右半部分。
        	left=number+1;
        	else
        	right=number;//是坏版本的话,选左半部分。
			      		
        }
        return left;//返回的是left=number+1,因为number不是坏版本,下一个就是坏版本的时候,就是第一个坏版本被找到的时候!
    }
}

  

原文地址:https://www.cnblogs.com/zhangfanxmian/p/6859710.html