74 第一個錯誤的代碼版本
阿新 • • 發佈:2018-07-06
tail lintcode tle svn ram 註釋 version 出錯 markdown
原題網址:https://www.lintcode.com/problem/first-bad-version/description
描述
代碼庫的版本號是從 1 到 n 的整數。某一天,有人提交了錯誤版本的代碼,因此造成自身及之後版本的代碼在單元測試中均出錯。請找出第一個錯誤的版本號。
你可以通過 isBadVersion
的接口來判斷版本號 version 是否在單元測試中出錯,具體接口詳情和調用方法請見代碼的註釋部分。
請閱讀上述代碼,對於不同的語言獲取正確的調用 isBadVersion 的方法,比如java的調用方式是SVNRepo.isBadVersion(v)
樣例
給出 n=5
調用isBadVersion(3)
,得到false
調用isBadVersion(5)
,得到true
調用isBadVersion(4)
,得到true
此時我們可以斷定4
是第一個錯誤的版本號
挑戰
調用 isBadVersion 的次數越少越好
思路:二分法。
lintcode又抽風,真是給跪了……看看這是什麽玩意
/**
* class SVNRepo {
* public:
* static bool isBadVersion(int k);
* }
* you can use SVNRepo::isBadVersion(k) to judge whether
* the kth code version is bad or not.
*/
class Solution {
public:
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
int findFirstBadVersion(int n) {
// write your code here
}
};
*/
class Solution {
public:
/*
* @param n: An integer
* @return: An integer which is the first bad version.
*/
int findFirstBadVersion(int n) {
// write your code here
}
};
以及,這道題隱藏著一個天坑——數據類型的問題,int是不夠的,要用long long,不信你試試,只通過90%的數據就超時了。
個破題提交好多次
AC代碼:
/**
* class SVNRepo {
* public:
* static bool isBadVersion(int k);
* }
* you can use SVNRepo::isBadVersion(k) to judge whether
* the kth code version is bad or not.
*/
class Solution {
public:
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
int findFirstBadVersion(int n) {
// write your code here
if (n<=0)
{
return 0;
}
long long l=1,r=n;
while(l<=r)
{
long long mid=(l+r)/2;
if (SVNRepo::isBadVersion(mid))
{
r=mid-1;
}
else
{
l=mid+1;
}
}
return l;
}
};
參考:
lintcode-74-第一個錯誤的代碼版本
https://blog.csdn.net/wangyuquanliuli/article/details/45900057
https://blog.csdn.net/orekinana/article/details/60138951
以下是我最開始的代碼:
/**
* class SVNRepo {
* public:
* static bool isBadVersion(int k);
* }
* you can use SVNRepo::isBadVersion(k) to judge whether
* the kth code version is bad or not.
*/
class Solution {
public:
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
int findFirstBadVersion(int n) {
// write your code here
if (n<=0)
{
return 0;
}
long long l=1,r=n;
while(l<=r)
{
long long mid=(l+r)/2;
if (SVNRepo::isBadVersion(mid))
{
if (mid==1)
{
return mid;
}
if (mid-1>=1&&SVNRepo::isBadVersion(mid-1)==false)
{
return mid;
}
r=mid-1;
}
else
{
l=mid+1;
}
}
}
};
74 第一個錯誤的代碼版本