278. First Bad Version

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.

题目含义:给定一系列版本号,要求找出第一个出错的版本号。(其中,当前的版本是基于前一个版本的,一旦某个版本出错,则当前版本后续的版本都会出错)

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

 

posted @ 2017-10-24 15:12  daniel456  阅读(125)  评论(0编辑  收藏  举报