Binary search
将nums[mid]转化为matrix[mid]
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
row = len(matrix)
col = len(matrix[0])
left = 0
right = row * col - 1
while left <= right:
mid = (left + right) // 2
if matrix[mid // col][mid % col] < target:
left = mid + 1
elif matrix[mid // col][mid % col] > target:
right = mid - 1
else:
return True
return False
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
# k的取值范围:[1,2,3,4,5,...,maxpiles]
left = 1
right = max(piles)
res = right
while left <= right:
cur_k = (left + right) // 2
total = 0
for pile in piles:
total += math.ceil(pile / cur_k)
if total > h:
left = cur_k + 1
else:
res = cur_k
right = cur_k - 1
return res
153. Find Minimum in Rotated Sorted Array
[4,5,1,2,3]
假设mid是最小的,用res暂存最小值
如果mid比left大: mid在左portion,应该向右边找
如果mid比left小:mid在右portion,应该向左边找
! 如果left已经比right小了---已经找到了单调的portion--跳出循环
class Solution:
def findMin(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1
res = 9999
while left <= right:
if nums[left] < nums[right]:
res = min(res, nums[left], nums[right])
# break
mid = (left + right) // 2
res = min(res, nums[mid])
if nums[mid] >= nums[left]:
left = mid + 1
else:
right = mid - 1
return res
递归
结果 = self.climbStairs(n-1) + self.climbStairs(n-2)