LeetCode 33: Search in Rotated Sorted Array

This problem is little difference to LeetCode 81. Search in Rotated Sorted Array II. In this problem, it assumes that no duplicate exists in the array.
Binary search is used to solve it. Iteration and recursion methods are implemented below.

1 Iteration

class Solution:
    def search(self, nums: 'List[int]', target: 'int') -> 'int':
        l, r = 0, len(nums) - 1
        while l <= r:
            
            mid = (l + r) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < nums[r]:
                if target >= nums[mid] and target <= nums[r]:
                    l = mid + 1
                else:
                    r = mid - 1
            else:
                if target >= nums[l] and target <= nums[mid]:
                    r = mid-1
                else:
                    l = mid + 1
        return -1

2 Recursion

class Solution:
    def search(self, nums: 'List[int]', target: 'int') -> 'int':
        def recursion(nums, l, r):
            if l <= r:
                mid = (l + r)//2
                if nums[mid] == target:
                    return mid
                if nums[mid] < nums[r]:
                    if target >= nums[mid] and target <= nums[r]:
                        l = mid + 1
                    else:
                        r = mid - 1
                else:
                    if target >= nums[l] and target <= nums[mid]:
                        r = mid - 1
                    else:
                        l = mid + 1
                return recursion(nums, l, r)
            else:
                return -1
        return recursion(nums, 0, len(nums) - 1)
点赞