Leetcode simple questions training set binary search の (278 367) python

Disclaimer: This article is original, All Rights Reserved https://blog.csdn.net/weixin_41864878/article/details/90676424

278. The first wrong version

You are a product manager, he is currently leading a team to develop new products. Unfortunately, the latest version of your product did not pass quality inspection. Since the previous version of the development of each version is based, so all later versions of the wrong version is wrong.

Suppose you have n versions [1, 2, ..., n], you want to find out first of all lead to the wrong version after version error.

You can call bool isBadVersion (version) interfaces to determine whether the version number version error in unit tests.
Implement a function to find the first incorrect version. You should try to reduce the number of API calls.

Example:

Given n = 5, and a first version = 4 is the wrong version.

Call isBadVersion (3) -> false
calls isBadVersion (5) -> true
calling isBadVersion (4) -> true

So 4 is the first wrong version.

class Solution(object):
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2: return n
        if n == 2:
            if isBadVersion(1): return 1
            else: return 2
        i = 1
        j = n
        while j > i:
            mid = int((j-i) / 2) + i
            if isBadVersion(mid):
                j = mid
            else: 
                i = mid+1
        return i

367. Effective perfect squares

Given a positive integer num, write a function, if num is a perfect square, then return True, otherwise False.

Note: Do not use any built-in library functions, such as sqrt.

Example 1:

Input: Output 16: True
Example 2:

Input: Output 14: False

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num < 9:
            if num == 1 or num == 4: return True
            else: return False

        start = 3
        end = int(num/2)
        while end > start:
            mid = int((end - start) / 2) + start
            if mid * mid == num: return True
            elif mid * mid > num:
                end = mid
            else:
                start = mid + 1
        return False     

Guess you like

Origin blog.csdn.net/weixin_41864878/article/details/90676424