孙晓聪
  • 最新
  • 博客
  • 书评
  • First Bad Version

    Description

    doc

    Solutions

    First Idea

    /**
     * Definition for isBadVersion()
     *
     * @param {integer} version number
     * @return {boolean} whether the version is bad
     * isBadVersion = function(version) {
     *     ...
     * };
     */
    
    /**
     * @param {function} isBadVersion()
     * @return {function}
     */
    var solution = function (isBadVersion) {
      /**
       * @param {integer} n Total versions
       * @return {integer} The first bad version
       */
      return function (n) {
        let low = 1
        let high = n
    
        while (low <= high) {
          const middle = low + Math.floor((high - low) / 2)
          if (low === middle) {
            return isBadVersion(low) ? low : low + 1
          }
    
          isBadVersion(middle) ? (high = middle) : (low = middle)
        }
    
        return -1
      }
    }
    
    • Time Complexity: O(logn)
    • Space Complexity: O(1)