-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirstBadVersion.py
49 lines (40 loc) · 1.25 KB
/
firstBadVersion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return an integer
# def isBadVersion(version):
class Solution:
# One approach can be stright brute force which would obviously give timeouts for large values of n
# Variation 1 of binary search :
def firstBadVersion1(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n
while(left < right):
mid = left + int((right-left)/2)
if( isBadVersion(mid) ):
right = mid
else:
left = mid + 1
return left
# Variation 2 of binary search (This approach is slightly faster than the upper one(4 ms faster lol):
def firstBadVersion2(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n
if(isBadVersion(left)):
return left
while(left < right):
mid = left + int((right-left)/2)
if( isBadVersion(mid) and isBadVersion(mid-1) == False ):
return mid
elif(isBadVersion(mid) == False):
left = mid + 1
else:
right = mid
return left