|
| 1 | +""" |
| 2 | +33. Search in Rotated Sorted Array |
| 3 | +https://leetcode.com/problems/search-in-rotated-sorted-array |
| 4 | +
|
| 5 | +Solution: Binary Search |
| 6 | + - Find the center of the array |
| 7 | + - Divide the array into two parts |
| 8 | + - Compare the left and right values of each part |
| 9 | + - If the target value is in the range of the left and right values of the first part, recursively call the function with the first part |
| 10 | + - If the target value is in the range of the left and right values of the second part, recursively call the function with the second part |
| 11 | + - If the first part is rotated, recursively call the function with the first part |
| 12 | + - Otherwise, recursively call the function with the second part |
| 13 | + - If the output is not -1, add the length of the first part to the output |
| 14 | +
|
| 15 | +Time complexity: O(log n) |
| 16 | + - The time complexity is the same as the time complexity of the binary search algorithm |
| 17 | +Space complexity: O(n) |
| 18 | + - Store the divided array in two variables |
| 19 | +""" |
| 20 | + |
| 21 | +from typing import List |
| 22 | + |
| 23 | + |
| 24 | +class Solution: |
| 25 | + def search(self, nums: List[int], target: int) -> int: |
| 26 | + if len(nums) == 1: |
| 27 | + if target == nums[0]: |
| 28 | + return 0 |
| 29 | + else: |
| 30 | + return -1 |
| 31 | + |
| 32 | + center = len(nums) // 2 |
| 33 | + arr1, arr2 = nums[:center], nums[center:] |
| 34 | + |
| 35 | + arr1_left, arr1_right = arr1[0], arr1[-1] |
| 36 | + arr2_left, arr2_right = arr2[0], arr2[-1] |
| 37 | + |
| 38 | + if arr1_left <= target <= arr1_right: |
| 39 | + output = self.search(arr1, target) |
| 40 | + |
| 41 | + elif arr2_left <= target <= arr2_right: |
| 42 | + output = self.search(arr2, target) |
| 43 | + |
| 44 | + if output != -1: |
| 45 | + output += len(arr1) |
| 46 | + |
| 47 | + elif arr1_right < arr1_left: |
| 48 | + output = self.search(arr1, target) |
| 49 | + else: |
| 50 | + output = self.search(arr2, target) |
| 51 | + |
| 52 | + if output != -1: |
| 53 | + output += len(arr1) |
| 54 | + return output |
0 commit comments