1. 程式人生 > >[Lintcode]74. First Bad Version/[Leetcode]278. First Bad Version

[Lintcode]74. First Bad Version/[Leetcode]278. First Bad Version

rom false pass earch The etc defined def 調用

[Lintcode]74. First Bad Version

[Leetcode]278. First Bad Version

  • 本題難度: [Lintcode]Medium/[Leetcode]
  • Topic: Binary Search

    Description

我的代碼 for Leetcode(在Lintcode中因為isBadVersion調用太多次無法通過)

# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):

class Solution:
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        if isBadVersion(1) is True:
            return 1
        else:
            if n==1:
                return 0
        l = 2
        r = n
        m = (l+r)//2
        while(l<=r):
            print(l,m,r)
            t1 = isBadVersion(m-1)
            t2 = isBadVersion(m)
            print(t1,t2)
            if t1 is False and t2 is True:
                print("ok")
                return m
            else:
                if t2 is False:
                    l = m+1
                else:
                    if t1 is True:
                        r = m-1
            m = (l+r)//2

別人的代碼 for Lintcode

#class SVNRepo:
#    @classmethod
#    def isBadVersion(cls, id)
#        # Run unit tests to check whether verison `id` is a bad version
#        # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a 
# bad version.
class Solution:
    """
    @param n: An integer
    @return: An integer which is the first bad version.
    """
    def findFirstBadVersion(self, n):
        # write your code here

        r = n-1
        l = 0
        while(l<=r):
            mid = l + (r-l)//2
            if SVNRepo.isBadVersion(mid)==False:
                l = mid+1
            else:
                r = mid-1
        return l

思路

大思路是二分法,但是我想岔了。
其實無需找到一個自身為true,前一個為false的id,只需要找到最後一個為false的id即可。這樣可以減少一次比較。

  • 時間復雜度: O(log(n))

[Lintcode]74. First Bad Version/[Leetcode]278. First Bad Version