69. x 的平方根
https://leetcode-cn.com/problems/sqrtx/
边界条件的判断是二分查找的唯一难点
start最终会留在平分刚好比x小的那个位置往右一点,也就是说
class Solution:
def mySqrt(self, x: int) -> int:
if x < 2:
return x
start = 0
end = x
while start <
= end:
midpoint = start + (end-start)//2
if midpoint * midpoint < x:
start = midpoint+1
elif midpoint * midpoint > x:
end = midpoint-1
else:
return midpoint
return start-1
153. 寻找旋转排序数组中的最小值
https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/
class Solution:
def findMin(self, nums: List[int]) -> int:
start = 0
end = len(nums)-1
while start<end:
midpoint = start + (end-start)//2
if nums[midpoint] > nums[end]:
start = midpoint+1
else:
end = midpoint
return nums[end]
33. 搜索旋转排序数组
https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
其实相对简单的办法还是先找到数组旋转点,也就是最小值在哪里,然后将数组分为两段,根据target和两段的关系来查找
注意等号的选择!
class Solution:
def search(self, nums: List[int], target: int) -> int:
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 target>=nums[left] and target<nums[mid]:
right = mid-1
else:
left = mid+1
else:
if target>nums[mid] and target<=nums[right]:
left = mid+1
else:
right = mid-1
return -1
1095. 山脉数组中查找目标值
https://leetcode-cn.com/problems/find-in-mountain-array/
有点类似在搜索旋转数组,但是这道题target有可能存在于左右两边各一个
关键在于先找到峰值,然后从峰值一分为二,在两侧都寻找
# """
# This is MountainArray's API interface.
# You should not implement it, or speculate about its implementation
# """
#class MountainArray:
# def get(self, index: int) -> int:
# def length(self) -> int:
class Solution:
def findMountainTop(self, mountain_arr: 'MountainArray') -> int:
left = 0
right = mountain_arr.length()-1
while left < right:
mid = left + (right-left)//2
mid_val = mountain_arr.get(mid)
if mid_val < mountain_arr.get(mid+1):
left = mid+1
else:
right = mid
return left
def binarySearch(self, arr, target, left, right, ascend=True):
while left <= right:
mid = left + (right-left)//2
if arr.get(mid) == target:
return mid
elif arr.get(mid) < target:
if ascend:
left = mid+1
else:
right = mid-1
else:
if ascend:
right = mid-1
else:
left = mid+1
return -1
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
peek_idx = self.findMountainTop(mountain_arr)
idx = self.binarySearch(mountain_arr, target, 0, peek_idx,True)
if idx!=-1:
return idx
else:
return self.binarySearch(mountain_arr, target, peek_idx, mountain_arr.length()-1, False)