leetcode 四道旋转有序数组相关的题
1、找到数组的最小值
leetcode154 数组有重复
leetcode153 数组无重复
和nums[right]比较
nums[mid]<nums[right] 右边有序 right=mid
nums[mid]>nums[right] 左边有序 left=mid+1
跟左边比,可能会错过最小值
两个问题共享同一份代码
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==1:
return nums[0]
left=0
right=len(nums)-1
while left<=right:
mid=left+(right-left)//2
if nums[mid]>nums[right]:
left=mid+1
elif nums[mid]<nums[right]:
right=mid
elif nums[mid]==nums[right]:
right-=1
return nums[left]
leetcode33 查找 数组不存在重复元素
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums)==0:
return -1
if len(nums)==1:
if nums[0]==target:
return 0
else:
return -1
left=0
right=len(nums)-1
while left<=right:
mid=left+(right-left)//2
if nums[mid]==target:
return mid
if nums[mid]>=nums[left]:
if nums[left]<=target and nums[mid]>=target:
right=mid-1
else:
left=mid+1
elif nums[mid]<nums[left]:
if nums[mid]<=target and nums[right]>=target:
left=mid+1
else:
right=mid-1
return -1
leetcode81 查找 数组存在重复元素
def search(self, nums: List[int], target: int) -> bool:
if len(nums)==0:
return False
if len(nums)==1:
if nums[0]==target:
return True
else:
return False
left=0
right=len(nums)-1
while left<=right:
mid=left+(right-left)//2
if nums[mid]==target:
return True
if nums[mid]==nums[left]:#!!
left+=1
elif nums[mid]>nums[left]:
if nums[left]<=target and nums[mid]>=target:
right=mid-1
else:
left=mid+1
elif nums[mid]<nums[left]:
if nums[mid]<=target and nums[right]>=target:
left=mid+1
else:
right=mid-1
return False