problem
solution1:遍历;
// Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int ver = 1; while(ver<n) { if(isBadVersion(ver)) return ver; ver++; } return ver; } };
solution2:二分法;
// Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int left = 1, right = n, mid; while(left<right) { mid = left + (right-left)/2; if(isBadVersion(mid)) right = mid; else left = mid + 1;//err. } return left; } };
参考
1. Leetcode_278_First Bad Version;
完