-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
45 lines (30 loc) · 1004 Bytes
/
main.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
# 33. Search in Rotated Sorted Array
# Time complexity: O(logn + logn), Space complexity: O(1)
def search(self, nums: List[int], target: int) -> int:
pivotIndex = self.findPivotIndex(nums)
left = 0
right = len(nums) - 1
if target >= nums[pivotIndex] and target <= nums[right]:
left = pivotIndex
else:
right = pivotIndex - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
if nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
# Time complexity: O(logn), Space complexity: O(1)
def findPivotIndex(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return left