Leetcode 278) First Bad Version
in Algorithms
내 답안
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
if(n==1){return 1;}
int l=0;
//template2 version
int r=n;
while(l<r){
int mid = l+(r-l)/2;
if(!isBadVersion(mid) && isBadVersion(mid+1)){
return mid+1;
}else if(isBadVersion(mid)){
r=mid;
}else{
l=mid+1;
}
}
return 1;
}
}
- api 덜 부르는 코드로 변경
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
if(n==1){return 1;}
int l=0;
//template2 version
int r=n;
while(l<r){
int mid = l+(r-l)/2;
boolean test=isBadVersion(mid);
if(!test){
if(isBadVersion(mid+1)){
return mid+1;
}else{
l=mid+1;
}
}else if(test){
r=mid;
}
}
return 1;
}
}
다른 답안
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int start=0; int end=n;
while(start<end)
{
int mid=start+(end-start)/2;
if(isBadVersion(mid))
{
end=mid;
}else{
start=mid+1;
}
}
return start;
}
}
중복된숫자가 있으면, 맨 처음거,