二分法有几种变形:
585 山脉序列中的最大值
first position of target
457 Classical Binary Search
458 Last Position of Target
他们的区别在于:
mountainSequence
二分也不能太死板呀,边界可以根据具体问题具体分析。
一定要给left = m1 + 1,要不然会超时
最后返回这个
else:
left = m1
right = m2
return max(nums[left], nums[right])
first position of target
只有两个if else,没有第三个if
457 Classical Binary Search
任意找一个
else:
return mid
458 Last Position of Target
else:
start = mid
用图片展示区别
四种方法程序:
二分查找 · first position of target
class Solution:
# @param nums: The integer array
# @param target: Target number to find
# @return the first position of target in nums, position start from 0
def binarySearch(self, nums, target):
# write your code here
left, right = 0, len(nums)
while left + 1 < right :