leetcode-1905-山脉数组中查找目标值

2021-02-02 22:17

阅读:484

标签:arch   ==   style   mono   span   mount   pac   二分   mil   

技术图片

 

方法:二分查找

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) ):
                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 
        mid = (l + r) // 2
        cur = key(mountain.get(mid))
        if cur == target:
            return mid
        elif cur 
            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 
            mid = (l + r) // 2
            if 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() - 1lambda x: -x)
        return index


leetcode-1905-山脉数组中查找目标值

标签:arch   ==   style   mono   span   mount   pac   二分   mil   

原文地址:https://www.cnblogs.com/oldby/p/12806697.html


评论


亲,登录后才可以留言!