码迷,mamicode.com
首页 > 其他好文 > 详细

Lettocde_278_First Bad Version

时间:2015-11-08 18:02:16      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   算法   面试   编程   

本文是在学习中的总结,欢迎转载但请注明出处: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;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

Lettocde_278_First Bad Version

标签:leetcode   java   算法   面试   编程   

原文地址:http://blog.csdn.net/pistolove/article/details/49719255

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!