-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path33.Search in Rotated Sorted Array.py
30 lines (28 loc) · 1.17 KB
/
33.Search in Rotated Sorted Array.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
class Solution(object):
def search(self, nums, target):
# print(nums) # print out current list during iterations
nums_len = len(nums)
if nums_len == 0:
return -1
mid = nums_len // 2
if nums[mid] == target:
return mid
elif nums_len == 1:
return -1 if target != nums[0] else 0
elif target < nums[mid]: # target is smaller, need to find a larger value
if mid < nums_len - 1 and nums[mid] >= nums[-1]:
result = self.search(nums[mid+1:].copy(), target)
if result != -1:
return result + mid + 1
return self.search(nums[:mid].copy(), target)
else: # target is larger
if mid > 0 and nums[0] >= nums[mid]:
result = self.search(nums[:mid].copy(), target)
if result != -1:
return result
result = self.search(nums[mid + 1:].copy(), target)
return mid + 1 + result if result != -1 else -1
if __name__ == '__main__':
array = [4,5,6,7,0,1,2]
target = 8
print(Solution().search(array, target))