First Bad Version
来源:互联网 发布:乌鲁木齐网络蛋糕店 编辑:程序博客网 时间:2024/06/15 05:20
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 whether version
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.
解题技巧:
采用二分查找法,并且主要在求mid的时候,采用mid = bg + (ed - bg)/2,如果使用mid = (bg + ed)/2,当bg、ed都很大时,可能发生数据溢出。
代码:
int firstBadVersion(int n) { int bg = 1, ed = n, mid; while(bg <= ed) { mid = bg + (ed - bg)/2; if(isBadVersion(mid)) { if(bg == ed) return bg; ed = mid; } else bg = mid+1; } }
- [刷题]First Bad Version
- first bad version
- First Bad Version
- [leetcode]First Bad Version
- First Bad Version
- LeetCode First Bad Version
- [leetcode] First Bad Version
- 278 First Bad Version
- 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#First Bad Version
- First Bad Version
- Ubuntu16.04下PX4 开发环境配置
- oracle连接数据库配置信息
- 数据压缩实验六--MPEG音频编码
- 《linux命令行与shell脚本编程大全》第三版
- 3
- First Bad Version
- 初见蓝桥--历年试题 兰顿蚂蚁
- LightOJ
- C#中三层架构UI、BLL、DAL、Model实际操作
- LeetCode 2. Add Two Numbers
- C#学习笔记:CheckedListBox控件的用法
- BZOJ 3098 Hash Killer II
- 【springmvc】springmvc框架
- 【面经笔记】面向对象