題目概述:
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。
我的代碼:
其他題目: