My LeetCode grinding. Trying to do a problem a day.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132
  1. # The isBadVersion API is already defined for you.
  2. # @param version, an integer
  3. # @return a bool
  4. # def isBadVersion(version):
  5. # I am assuming that the latest definitely is bad based on the way the problem is worded
  6. # so I will just implement a binary search pretty mcuh
  7. def isBadVersion(n):
  8. return n >= 4
  9. class Solution:
  10. def firstBadVersion(self, n):
  11. # This check cuts out a case quickly, and also makes the logic easier to write
  12. # because negatives and zeros no longer have to be dealt with
  13. if isBadVersion(0):
  14. return 0
  15. knownGood = 0
  16. knownBad = n
  17. while knownBad - knownGood > 1:
  18. # find the mid point
  19. # check whether it's good or bad, and update accordingly
  20. mid = (knownGood + knownBad) // 2
  21. if isBadVersion(mid):
  22. knownBad = mid
  23. else:
  24. knownGood = mid
  25. return knownBad
  26. s = Solution()
  27. print("Expected: 4")
  28. print("Got:", s.firstBadVersion(5))