首页 > 其他 > 详细

First Bad Version

时间:2016-07-16 06:57:51      阅读:198      评论:0      收藏:0      [点我收藏+]

The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version.

You can call isBadVersion to help you determine which version is the first bad one. The details interface can be found in the code‘s annotation part.

 Notice

Please read the annotation in code area to get the correct way to call isBadVersion in different language. For example, Java is SVNRepo.isBadVersion(v)

Example

Given n = 5:

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

Here we are 100% sure that the 4th version is the first bad version.

分析:

二分查找。

 1 /**
 2  * public class SVNRepo {
 3  *     public static boolean isBadVersion(int k);
 4  * }
 5  * you can use SVNRepo.isBadVersion(k) to judge whether 
 6  * the kth code version is bad or not.
 7 */
 8 class Solution {
 9     /**
10      * @param n: An integers.
11      * @return: An integer which is the first bad version.
12      */
13     public int findFirstBadVersion(int n) {
14         int start = 1;
15         int end = n;
16         
17         while (start <= end) {
18             int mid = (start + end) / 2;
19             if (SVNRepo.isBadVersion(mid) == false) {
20                 start = mid + 1;
21             } else {
22                 end = mid - 1;
23             }
24         }
25         
26         return start;
27     }
28 }

 

First Bad Version

原文:http://www.cnblogs.com/beiyeqingteng/p/5675205.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!