版权声明:本文章为博主原创,转载请注明出处。保留所有权利。

Contents
  1. 1. 题目
  2. 2. 解析

Leetcode-278的解题过程。

  • 题目

    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.

  • 解析

      Easy级别的题目,给定一个从1到n的数组,以及一个判定bad version的API,要找到第一个bad version的版本号。bad version是向后影响的,即第一个bad version后面的所有版本全部都是bad version。根据这个特点直接运用二分查找就可以了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    /* The isBadVersion API is defined in the parent class VersionControl.
    bool IsBadVersion(int version); */

    public class Solution : VersionControl {
    public int FirstBadVersion(int n) {
    //这里有个坑,testcase里面的版本号有的超过了int最大值,在循环的条件判断时会出问题,所以用long
    long a = 1;
    long b = n;

    while(b-a>1){
    long t = (b+a)/2;
    if (IsBadVersion((int)t)){
    b = t;
    }else{
    a = t;
    }

    }
    if (IsBadVersion((int)a))
    return (int)a;
    else
    return (int)b;

    }
    }

打赏

取消
扫码支持

你的支持是对我最好的鼓励

Contents
  1. 1. 题目
  2. 2. 解析