81. 搜索旋转排序数组 II

二分查找

  1. 找到第二个有序数组的起始索引
  2. 对两个有序数组进行二分查找
class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        
        # 找第二个有序数组的起始索引
        k = 0
        
        while k < len(nums) - 1 and nums[k] <= nums[k + 1]:
            k += 1
            
        k += 1
        
        return self.binary_search(nums[:k], target) or self.binary_search(nums[k:], target)
        
    
    
    def binary_search(self, nums, target):
        
        l = 0
        r = len(nums) - 1
        
        while l <= r:
            mid = (l + r) // 2
            
            if nums[mid] == target:
                return True
            
            elif nums[mid] > target:
                r = mid - 1
            else:
                l = mid + 1
                
        return False

相关文章:

  • 2022-12-23
  • 2021-07-04
  • 2021-07-04
  • 2021-09-23
  • 2021-05-26
  • 2021-05-12
猜你喜欢
  • 2021-08-15
  • 2022-02-21
  • 2022-12-23
  • 2022-01-04
  • 2022-02-22
  • 2021-06-06
  • 2022-12-23
相关资源
相似解决方案