Skip to content

Commit eb00f9c

Browse files
committed
Search in rotated sorted array solution
1 parent 6eb0714 commit eb00f9c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

33_search_in_rotated_sorted_array.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def search(self, nums, target):
3+
"""
4+
:type nums: List[int]
5+
:type target: int
6+
:rtype: int
7+
"""
8+
# binary search
9+
# if start < mid, then left part is sorted
10+
# if mid < end, then right part is sorted
11+
def get(start, end):
12+
if start > end:
13+
return -1
14+
mid = (start + end) / 2
15+
if nums[mid] == target:
16+
return mid
17+
elif nums[mid] >= nums[start]: # First half is sorted
18+
if target >= nums[start] and target < nums[mid]:
19+
return get(start, mid - 1)
20+
else:
21+
return get(mid + 1, end)
22+
elif nums[mid] <= nums[end]: # Second half is sorted
23+
if target > nums[mid] and target <= nums[end]:
24+
return get(mid + 1, end)
25+
else:
26+
return get(start, mid - 1)
27+
return get(0, len(nums) - 1)

0 commit comments

Comments
 (0)