6/04/2020

[LeetCode] 81. Search in Rotated Sorted Array II

Problem : https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

When nums[mid] < nums[right], the right part is sorted.
When nums[mid] > nums[right], the left part is sorted.
When nums[mid] == nums[right], shrink the right part.

class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        left, right = 0, len(nums) - 1
        
        while left <= right:
            mid = left + (right - left) // 2
            
            if nums[mid] == target:
                return True
            
            if nums[mid] < nums[right]:
                # right part is sorted
                if  nums[mid] < target <= nums[right]:
                    left = mid + 1
                else:
                    right = mid - 1
            elif nums[mid] > nums[right]:
                # left part is sorted
                
                if nums[left] <= target < nums[mid]:
                    right = mid - 1
                else:
                    left = mid + 1
            else:
                # nums[mid] == nums[right]
                # bypass current nums[right]
                right -= 1
                    
        return False

No comments:

Post a Comment