zoukankan      html  css  js  c++  java
  • [leetcode]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.

    Given n = 5
    
    call isBadVersion(3) -> false
    call isBadVersion(5) -> true
    call isBadVersion(4) -> true
    
    Then 4 is the first bad version. 

    题意:

    思路:

    二分查找。 

    注意的是,每个人的二分查找模板可能都不同。

    源于对left和right的初始化不同。一旦定义好了left和right的区间,就要在之后的代码里维护好这个区间。

    举例,

     

    定义好left = 0, right = n-1, 则在[left...right] 范围内找target,极端情况下left会一直靠向right直至等于right。 

     1   private int binarySearch2(int n, int[]arr, int target){
     2         int l = 0, r = n-1 ;
     3         while(l <= r){
     4             int mid = l+(r-l)/2;
     5             if(arr[mid] == target){
     6                 return mid;
     7             }else if(target > arr[mid]){
     8                 l = mid + 1;
     9             }else {
    10                 r = mid-1 ;
    11             }
    12         }
    13         return -1;
    14     }

    定义好left = 0, right = n, 则在 [left...right) 范围内找target,极端情况下left会一直靠向right但不能等于right。 

     1    private int binarySearch(int n, int[]arr, int target){
     2         int l = 0, r = n ;
     3         while(l < r){
     4             int mid = l+(r-l)/2;
     5             if(arr[mid] == target){
     6                 return mid;
     7             }else if(target > arr[mid]){
     8                 l = mid + 1;
     9             }else {
    10                 r = mid ;
    11             }
    12         }
    13         return -1;
    14     }

    当然, 与此相对应的,也可以初始化 left = -1, 思路一致。 选择一套自己好理解的模板,白子偕老。

    代码:

     1 public class FirstBadVersion {
     2     public int firstBadVersion(int n) {
     3         int left = 1, right = n - 1;
     4         while (left <= right) {
     5             int mid = left + (right - left) / 2;
     6             if (!isBadVersion(mid)) {
     7                 left = mid + 1;
     8             } else {
     9                 right = mid - 1;
    10             }
    11         }
    12         return left;
    13     }
    14 }
  • 相关阅读:
    深入理解CSS中的层叠上下文和层叠顺序
    利用CSS3制作淡入淡出动画效果
    <link>标签的rel属性全解析
    解决<pre>标签里的文本换行(兼容IE, FF和Opera等)
    HTML特殊字符大全
    清除浮动4种方法总结下
    打开wamp中的phpmyadmin出现403的错误
    js访问CSS最终计算样式
    js 正则 exec() 和 match() 数据抽取
    函数表达式中,函数名称在函数体内是只读的
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9120785.html
Copyright © 2011-2022 走看看