81. 搜索旋转排序数组 II
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,0,1,2,2,5,6]
可能变为 [2,5,6,0,0,1,2]
)。
编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true
,否则返回 false
。
示例 1:
输入: nums = [2,5,6,0,0,1,2]
, target = 0
输出: true
示例 2:
输入: nums = [2,5,6,0,0,1,2]
, target = 3
输出: false
进阶:
nums
可能包含重复元素。class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if not nums:return False
l,r = 0,len(nums) - 1
while l <= r:
m = (l+r) // 2
if nums[m] == target:return True
#如果中间的数小于最右边的数,则右半段是有序的,若中间数大于最右边数,则左半段是有序的。
elif nums[m] < nums[r]:
if nums[m] < target <= nums[r]:l = m + 1
else:r = m - 1
elif nums[m] > nums[r]:
if nums[l] <= target < nums[m]:r = m - 1
else:l = m + 1
else:
r -= 1
return False
pythonic解法:
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
return True if target in nums else False