-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch-in-rotated-sorted-array.py
More file actions
32 lines (27 loc) · 996 Bytes
/
search-in-rotated-sorted-array.py
File metadata and controls
32 lines (27 loc) · 996 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from typing import List
class Solution:
# Time complexity: O(log n) where n is the length of nums
# Space complexity: O(1)
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] < target:
if nums[mid] < nums[-1]: # right part
if target > nums[-1]:
right = mid-1
else:
left = mid+1
else: # left part
left = mid+1
elif nums[mid] > target:
if nums[mid] < nums[-1]: # right part
right = mid-1
else: # left part
if target < nums[0]:
left = mid+1
else:
right = mid-1
else:
return mid
return -1