-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsoluton.py
59 lines (54 loc) · 1.78 KB
/
soluton.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def find_rotate_index(left, right):
if nums[left] < nums[right]:
return 0
while left <= right:
pivot = (left + right) // 2
if nums[pivot] > nums[pivot + 1]:
return pivot + 1
else:
if nums[pivot] < nums[left]:
right = pivot - 1
else:
left = pivot + 1
def search(left, right):
"""
Binary search
"""
while left <= right:
pivot = (left + right) // 2
if nums[pivot] == target:
return pivot
else:
if target < nums[pivot]:
right = pivot - 1
else:
left = pivot + 1
return -1
n = len(nums)
if n == 0:
return -1
if n == 1:
return 0 if nums[0] == target else -1
rotate_index = find_rotate_index(0, n - 1)
print(rotate_index)
# if target is the smallest element
if nums[rotate_index] == target:
return rotate_index
# if array is not rotated, search in the entire array
if rotate_index == 0:
return search(0, n - 1)
if target < nums[0]:
# search on the right side
return search(rotate_index, n - 1)
print("search on the left side")
return search(0, rotate_index)
array=[4,3,5,6,7]
target=7
print(Solution().search(array,target))