[leet code] 278. First Bad Version

Su-hyeon B·2022년 12월 16일
0

알고리즘 문제 풀이

목록 보기
67/70
post-custom-banner

Question

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 returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

//since the given array is sorted array, I will use binary search

class Solution {
public:
    int firstBadVersion(int n) {
        int left=1; 
        int right = n;
        int middle;
        
        while(left <right){
            //middle = (left+right)2; 범위 오류남
            middle = left +(right-left)/2;
            if(isBadVersion(middle))
                right = middle;
            else
                left = middle+1;
            
        }
        return right;
    }
};
profile
ML/AI Engineer
post-custom-banner

0개의 댓글