알고리즘

[LeetCode] 278. First Bad Version

유병각 2022. 4. 24. 15:01

https://leetcode.com/problems/first-bad-version/

[LeetCode] 278. First Bad 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
        """
        low = 1
        finish = n

        if (isBadVersion(1)):
            return 1

        while (low <= finish):
            mid = int(low + (finish - low) // 2)

            if (isBadVersion(mid) and not isBadVersion(mid-1)):
                return mid
            elif (isBadVersion(mid)):
                finish = mid - 1
            elif (not isBadVersion(mid)):
                low = mid + 1