-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0081-search-in-rotated-sorted-array-ii.py
More file actions
37 lines (32 loc) · 1.04 KB
/
0081-search-in-rotated-sorted-array-ii.py
File metadata and controls
37 lines (32 loc) · 1.04 KB
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
# time complexity: O(logn)
# space complexity: O(1)
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> bool:
left = 0
right = len(nums) - 1
while left <= right:
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
mid = (left + right) // 2
if nums[mid] == target:
return True
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return False
nums = [2, 5, 6, 0, 0, 1, 2]
target = 0
print(Solution().search(nums, target))
nums = [2, 5, 6, 0, 0, 1, 2]
target = 3
print(Solution().search(nums, target))