本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49719255
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)题意为给定一系列版本号,要求找出第一个出错的版本号。(其中,当前的版本是基于前一个版本的,一旦某个版本出错,则当前版本后续的版本都会出错)
(2)该题主要考察二分查找。可以把1,2,...n一系列版本表示为 good,good,......,good,bad, bad,.....,只需通过二分查找算法进行判断,需要注意的是:如果发现当前版本是好的,则需要将start指向mid的下一个位置。
(3)详情见下方代码。希望本文对你有所帮助。
package leetcode; public class First_Bad_Version { // 找出第一个坏的 public int firstBadVersion(int n) { int start = 0; int end = n; while(start <=end) { int mid = start +(end -start) >> 1; // 是坏的,则从当前往后找 if(isBadVersion(mid)){ end = mid; }else { start = mid + 1; } } return end; } static boolean isBadVersion(int version){ return true; } }