leetcode-1905-山脉数组中查找目标值
Posted 真不知道叫啥好
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-1905-山脉数组中查找目标值相关的知识,希望对你有一定的参考价值。
方法:二分查找
def binary_search(mountain, target, l, r, key=lambda x: x): target = key(target) while l <= r: mid = (l + r) // 2 cur = key(mountain.get(mid)) if cur == target: return mid elif cur < target: l = mid + 1 else: r = mid - 1 return -1 class Solution: def findInMountainArray(self, target: int, mountain_arr: \'MountainArray\') -> int: l, r = 0, mountain_arr.length() - 1 while l < r: mid = (l + r) // 2 if mountain_arr.get(mid) < mountain_arr.get(mid + 1): l = mid + 1 else: r = mid peak = l index = binary_search(mountain_arr, target, 0, peak) if index != -1: return index index = binary_search(mountain_arr, target, peak + 1, mountain_arr.length() - 1, lambda x: -x) return index
def binary_search(mountain, target, l, r, key=lambda x: x):
target = key(target)
while l <= r:
mid = (l + r) // 2
cur = key(mountain.get(mid))
if cur == target:
return mid
elif cur < target:
l = mid + 1
else:
r = mid - 1
return -1
class Solution:
def findInMountainArray(self, target: int, mountain_arr: \'MountainArray\') -> int:
l, r = 0, mountain_arr.length() - 1
while l < r:
mid = (l + r) // 2
if mountain_arr.get(mid) < mountain_arr.get(mid + 1):
l = mid + 1
else:
r = mid
peak = l
index = binary_search(mountain_arr, target, 0, peak)
if index != -1:
return index
index = binary_search(mountain_arr, target, peak + 1, mountain_arr.length() - 1, lambda x: -x)
return index
以上是关于leetcode-1905-山脉数组中查找目标值的主要内容,如果未能解决你的问题,请参考以下文章