【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 returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

Constraints:

  • 1 <= bad <= n <= 231 - 1

Thought:

  • Binary search典型题
  • 与之前所不一致的是,题目中隐含着搜索序列,从后向前
  • 其他的便是二分法常见套路,注意使用isBadVersion所给函数判定。

AC

/*
 * @lc app=leetcode.cn id=278 lang=cpp
 *
 * [278] 第一个错误的版本
 */

// @lc code=start
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

class Solution {
    
    
public:
    int firstBadVersion(int n) {
    
    
        int left = 1, right = n;
        while(left < right)
        {
    
    
            int mid = left + (right - left) / 2;
            if(isBadVersion(mid))
            {
    
    
                right = mid;
            }
            else
            {
    
    
                left = mid + 1;
            }
        }
        return left;
    }
};
// @lc code=end

AC


Supplement

  • 二分法是一种基本的算法思想,也叫折半查找,是一种在有序数组中查找某一特定元素的搜索算法。 C++中实现二分法的步骤如下:
  1. 确定二分的初始范围,一般是整个数组范围。

  2. 通过计算中间位置的下标,找出中间元素,然后与目标元素进行比较。

  3. 如果中间元素等于目标元素,则查找结束。

  4. 如果中间元素大于目标元素,则新的查找范围在数组左半部分。

  5. 如果中间元素小于目标元素,则新的查找范围在数组右半部分。

  6. 重复2-5步骤,直到找到目标元素或者数组被搜索完毕。

C++代码示例:

int binarySearch(int arr[], int left, int right, int x) {
    
    
    while (left <= right) {
    
    
        int mid = left + (right - left) / 2;
        if (arr[mid] == x) {
    
    
            return mid;
        } else if (arr[mid] < x) {
    
    
            left = mid + 1;
        } else {
    
    
            right = mid - 1;
        }
    }
    return -1;
}

在上面的代码中,arr为有序数组,leftright是数组的左右边界,x为目标元素。程序返回目标元素在数组中的下标,如果目标元素不存在,则返回-1

猜你喜欢

转载自blog.csdn.net/qq_54053990/article/details/131271304