【LeetCode & 劍指offer刷題】查詢與排序題10:First Bad Version
阿新 • • 發佈:2019-01-05
【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)
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.C++ // Forward declaration of isBadVersion API. bool isBadVersion ( int version ); //序列可看成(0,0,0,0,1,1,1,1,1,1,1,1,1,1)找第一個為1的數(可用lower_bound函式) class Solution { public : int firstBadVersion ( int n ) //版本序列為有序序列,可用二分查詢 { int left = 1 , mid , right = n ; while ( left <= right ) //這裡也可以寫成< { mid = left + ( right - left )/ 2 ; //防止(left+right)/2造成溢位風險 if (! isBadVersion ( mid )) { left = mid + 1 ; //為0時往右邊找,left會移動到第一個為1的數的位置 } else { right = mid - 1 ; //為1時往左邊找,也可以寫成right=mid } } if ( isBadVersion ( left )) return left ; else return - 1 ; //如果找不到就返回-1 } }; /* //一般的二分查詢 while(left <= right) //注意這裡為<=,因為要計算一次mid再返回 { mid = left + (right - left)/2; //防止(left+right)/2造成溢位風險 if(a[mid]<key) { left = mid + 1; } else if(a[mid]>key) { right = mid -1; } else { return mid; } } */