Skip to content

Commit c94b44c

Browse files
committed
solve: searchInRotatedSortedArray
1 parent 5d7e549 commit c94b44c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time Complexity: O(log n) - using a modified binary search,
2+
# Space Complexity: O(1) - no extra space used, just a few variables.
3+
4+
class Solution:
5+
def search(self, nums: List[int], target: int) -> int:
6+
# default result, in case the target isn't found
7+
res = -1
8+
# set up the binary search range
9+
left, right = 0, len(nums) - 1
10+
11+
while left <= right:
12+
# calculate the middle index
13+
mid = left + (right - left) // 2
14+
15+
# found the target, store the index
16+
if nums[mid] == target:
17+
res = mid
18+
19+
# check if the left half is sorted
20+
if nums[left] <= nums[mid]:
21+
if nums[left] <= target < nums[mid]:
22+
# target in the left half, move right pointer
23+
right = mid - 1
24+
else:
25+
# otherwise, search in the right half
26+
left = mid + 1
27+
28+
# otherwise, the right half must be sorted
29+
else:
30+
if nums[mid] < target <= nums[right]:
31+
# target in the right half, move left pointer
32+
left = mid + 1
33+
else:
34+
# otherwise, search in the left half
35+
right = mid - 1
36+
37+
return res

0 commit comments

Comments
 (0)