-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path33.py
76 lines (60 loc) · 1.63 KB
/
33.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
73
74
75
76
from typing import List
# Name: Search in Rotated Sorted Array
# Link: https://leetcode.com/problems/search-in-rotated-sorted-array/
# Method: Binary search to find pivot, and then to find elem in sorted section
# Time: O(log(n))
# Space: O(1)
# Difficulty: Medium
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
if not nums:
return -1
l = 0
h = n
pivot = 0
while l < h:
mid = (l + h) // 2
x = nums[mid]
if mid + 1 < n and x > nums[mid + 1]:
pivot = mid + 1
break
elif mid > 1 and x < nums[mid - 1]:
pivot = mid
break
elif x > nums[0]:
l = mid + 1
elif x < nums[-1]:
h = mid
else:
print(f"Oh no, in case l: {l} h:{h} mid:{mid}")
pivot = 1
break
print(f"Pivot at {pivot}")
l = 0
h = n
while l <= h:
mid = (l + h) // 2
i = (mid + pivot) % n
x = nums[i]
if x == target:
return i
elif x < target:
l = mid + 1
elif x > target:
h = mid - 1
return -1
if __name__ == "__main__":
sol = Solution()
inp = [4, 5, 6, 7, 0, 1, 2]
t = 10
print(sol.search(inp, t))
inp = [4, 5]
t = 5
print(f"{sol.search(inp, t)} is 1")
inp = [4, 5]
t = 4
print(f"{sol.search(inp, t)} is 0")
intp = [5, 4]
t = 5
print(f"{sol.search(inp, t)} is 0")