值域二分

0X00 模板题目

  • 278. First Bad Version

判断能不能用值域二分的关键在于:

  • 我们找的这个值能不能把原数组一分为二, 自己就是那个临界值
class Solution:
    def firstBadVersion(self, n):
        left, right = 1, n
        while left < right:
            mid = left + (right - left) // 2
            if not isBadVersion(mid):
                left = mid + 1
            else:
                right = mid
        
        return right
  • 69. Sqrt(x)
class Solution:
    def mySqrt(self, x: int) -> int:
        left, right = 1, x

        while left <= right:
            mid = left + (right - left) // 2
            t = mid ** 2
            if  t == x: return mid
            elif t < x: left = mid + 1
            else: right = mid - 1
        
        return right

0X01 注意事项

暂无

0X02 相关题目

  • 278. First Bad Version

  • 69. Sqrt(x)

  • 287. Find the Duplicate Number

  • 644. Maximum Average Subarray II

  • 1292. Maximum Side Length of a Square with Sum Less than or Equa(这道题要好做)

你可能感兴趣的:(值域二分)