File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments