-
Notifications
You must be signed in to change notification settings - Fork 1
/
33. Search in Rotated Sorted Array.py
72 lines (69 loc) · 2.55 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
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
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
Runtime: 88 ms, faster than 38.01% of Python3 online submissions for Search in Rotated Sorted Array.
Memory Usage: 14.8 MB, less than 22.57% of Python3 online submissions for Search in Rotated Sorted Array.
Out of range of graphs it was so bad!
The problem was the use of recusion.
Maybe you should not use recursion!
"""
class Solution:
#def search(self, nums: List[int], target: int) -> int:
def search(self, nums: list, target: int) -> int:
#
def search_in_sorted_part(nums: list, target: int):
n = len(nums)
if n == 0:
return -1
elif nums[n//2] == target:
return n//2
elif nums[n//2] > target:
res = search_in_sorted_part(nums[0:n//2:], target)
if res == -1:
return -1
else:
return res
else: #nums[n//2] < target:
res = search_in_sorted_part(nums[(n//2)+1::],target)
if res == -1:
return -1
else:
return n//2 + 1 + res
#
def search_in_roteted_list(nums: list,target: int):
n = len(nums)
if n <3:
for k in range(n):
if nums[k] == target:
return k
return -1
if nums[0] < nums[n//2]:
if nums[0] <= target and target <= nums[n//2]:
res = search_in_sorted_part(nums[0:(n//2)+1:],target)
if res == -1:
return -1
else:
return res
else: # target < nums[0] or nums[n//2] < target
res = search_in_roteted_list(nums[(n//2) +1::1],target)
if res == -1:
return -1
else:
return n//2 + 1 + res
else:
if nums[n//2 + 1] <= target and target <= nums[n-1]:
res = search_in_sorted_part(nums[(n//2) +1::1],target)
if res == -1:
return -1
else:
return n//2 + 1 + res
else:
res = search_in_roteted_list(nums[0:(n//2)+1:],target)
if res == -1:
return -1
else:
return res
return search_in_roteted_list(nums,target)
sol = Solution()
nums = [3]
target = 3
i = sol.search(nums,target)
print(i)