不解释,一样的套路嘛。
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
return mid
return -1
852 这道山峰题,注意没有等号,所以直接判断递增规律就好。
因为 length >= 3,所以可用 mid - 1 和 mid + 1,这可能是二分的一个突破。也可直接跑最大值索引......
class Solution(object):
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
# return A.index(max(A))
left, right = 0, len(A) - 1
while left <= right:
mid = (left +right) / 2
if A[mid - 1] < A[mid] and A[mid] < A[mid + 1]:
left = mid + 1
elif A[mid] > A[mid + 1] and A[mid - 1] > A[mid]:
right = mid - 1
else:
return mid
网友评论