[LeetCode] 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 boolisBadVersion(version) which will return whetherversion is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
题目解析:
数组[1,2..n]中存在一个bad版本时,后面的版本都是bad,通过调用函数isBadVersion可以判断是否是bad版本。例如:[1,2,3]中2是bad版本,则调用isBadVersion(2)=true、isBadVersion(1)=false、isBadVersion(3)=true,结果返回2第一个导致bad的版本。
解决方法:二分查找
需注意middle=left+(right-left)/2、二分查找的下标移动和返回值left。
我的代码:
- 点赞
- 收藏
- 关注作者
评论(0)