[LeetCode] First Bad Version - 二分查找
生活随笔
收集整理的這篇文章主要介紹了
[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。
我的代碼:
// Forward declaration of isBadVersion API. bool isBadVersion(int version);/** 二分查找 關鍵步驟:* 1.middle定位 * 2.大于middle查找右部分 left=middle+1* 3.小于middle查找左部分 right=middle-1*/ int firstBadVersion(int n) {int middle;int left;int right;left=1;right=n;while(left<=right) {middle = left+(right-left)/2; //重點&能防止越界 例1+(5-1)/2=3if(isBadVersion(middle)==true) {right = middle-1;}else {left = middle+1;}}return left; }
其他題目:
(By:Eastmount 2015-9-9 凌晨2點 ??http://blog.csdn.net/eastmount/)
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。
我的代碼:
// Forward declaration of isBadVersion API. bool isBadVersion(int version);/** 二分查找 關鍵步驟:* 1.middle定位 * 2.大于middle查找右部分 left=middle+1* 3.小于middle查找左部分 right=middle-1*/ int firstBadVersion(int n) {int middle;int left;int right;left=1;right=n;while(left<=right) {middle = left+(right-left)/2; //重點&能防止越界 例1+(5-1)/2=3if(isBadVersion(middle)==true) {right = middle-1;}else {left = middle+1;}}return left; }
其他題目:
(By:Eastmount 2015-9-9 凌晨2點 ??http://blog.csdn.net/eastmount/)
總結
以上是生活随笔為你收集整理的[LeetCode] First Bad Version - 二分查找的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [LeetCode] Binary Tr
- 下一篇: [LeetCode] Plus One