278. First Bad Version [easy] (Python)
2016-07-27 18:19
405 查看
题目链接
https://leetcode.com/problems/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
nversions
[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
versionis bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
题目翻译
大概意思就是:假设你有n个版本号 [1, 2, …, n], 其中从某个版本号开始往后的所有版本都是错误版本,你想找到第一个错误的版本号。你可以调用一个预实现的接口
bool isBadVersion(version),它会返回输入的版本号
version是否是错误版本号。你需要实现一个找到第一个错误版本号的函数,尽量少的调用该接口。
思路方法
思路一
暴力顺序搜索会超时,符合题意要采用二分搜索法。这里稍微需要注意的是,你要找的元素应该符合这样的特征:或者它是第一个版本号,或者它是错误版本号且它前一个版本号是正确版本号。代码
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ left, right = 1, n while True: mid = (left + right) / 2 if isBadVersion(mid): if mid == 1 or not isBadVersion(mid - 1): return mid right = mid - 1 else: left = mid + 1
思路二
类似上面的思路,其实可以不对错误的版本号进行特殊的判断操作,而是在缩小搜索范围时仍将当前错误版本号包含在新的区间内,那么最终区间只有一个元素时即为所求。代码
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ left, right = 1, n while left < right: mid = (left + right) / 2 if isBadVersion(mid): right = mid else: left = mid + 1 return left
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52048093
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法