Algorithm/LeetCode

[LeetCode] 278. First Bad Version

rrojin 2022. 2. 28. 12:45

문제링크

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

 

First Bad Version - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:
 
class Solution:
    def firstBadVersion(self, n: int-> int:
        left, right = 1, n
       
        while left<=right:
            pivot = (left+right)//2
            if isBadVersion(pivot):
                if not isBadVersion(pivot-1):
                    return pivot
                else:
                    right = pivot-1
            else:
                left = pivot+1
cs

 

POINT

- 풀이방법:

Binary Search로 접근한다.

isBadVersion(pivot)이 False이면 left를 pivot+1로 옮기고,

True이면 right를 pivot-1로 옮겨서 범위를 좁혀나가며 탐색한다.

 

- Complexity Analysis:

1) Time Complexity : O(log n)

2) Space Complexity: O(1)

'Algorithm > LeetCode' 카테고리의 다른 글

[LeetCode] 283. Move Zeroes  (0) 2022.03.02
[LeetCode] 189. Rotate Array  (0) 2022.03.01
[LeetCode] 977. Squares of a Sorted Array  (0) 2022.03.01
[LeetCode] 35. Search Insert Position  (0) 2022.02.28
[LeetCode] 704. Binary Search  (0) 2022.02.28