LeetCode:First Bad Version
来源:互联网 发布:php fread函数的用法 编辑:程序博客网 时间:2024/04/28 05:11
问题描述:
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 bool isBadVersion(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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路:
1、采用二分查找法找到当前版本为坏版本,但是前一版本为好版本;
2、注意边界情况的处理,特别是头尾;
3、如果没有找到,返回-1;
代码:
// Forward declaration of isBadVersion API.bool isBadVersion(int version);class Solution {public: int firstBadVersion(int n) { if(n < 1) { return -1; } int low = 1; int high = n; int mid; while(low + 1 < high) { mid = low + (high - low) / 2; if(isBadVersion(mid)) { high = mid; // 从前半段开始找 } else { low = mid; //从后半段开始找 } } if (isBadVersion(low)) { return low; } else if (isBadVersion(high)) { return high; } return -1; }};
- [leetcode]First Bad Version
- LeetCode First Bad Version
- [leetcode] First Bad Version
- [Leetcode]First Bad Version
- Leetcode: First Bad Version
- leetcode First Bad Version
- LeetCode || First Bad Version
- [leetcode]First Bad Version
- Leetcode: First Bad Version
- #leetcode#First Bad Version
- leetcode:First Bad Version
- LeetCode-First Bad Version
- [LeetCode]First Bad Version
- [LeetCode]First Bad Version
- leetcode-First Bad Version
- [LeetCode]First Bad Version
- First Bad Version -- leetcode
- leetcode --First Bad Version
- 线段树(2)区间修改
- 欢迎使用CSDN-markdown编辑器
- iOS UI设计: autolayout约束的一点技巧
- node个人博客第一天
- MyEclipse优化设置(最详细版本)
- LeetCode:First Bad Version
- C# 零散笔记
- 好好生活
- RTC实时时钟驱动
- 排序算法(三)------冒泡排序和快速排序
- PHP会话处理相关函数介绍
- 《用户体验要素》读书笔记
- C++运算符重载详解
- fs4412开发板学习笔记(六)