查找数组中的最大元素,先升序再降序

Finding the max element in an array, sorted ascending first and then descending

我尝试了一个在线挑战,其中有一个问题如下:

You are given an array which increases at first and then starts decreasing. For example: 2 3 4 5 6 7 8 6 4 2 0 -2. Find the maximum element of these array.

以下是我使用二进制搜索的代码,它在 O(log(n)) 中给出了正确答案,但我不知道是否有更好的解决方案。 有人可以帮我吗?

a= map(int, raw_input().split())
def BS(lo,hi):
    mid = lo+ (hi-lo)/2
    if a[mid]>=a[mid+1]:
        if a[mid]>a[mid-1]:
            return mid
        else:
            return BS(lo,mid)
    else:
        return BS(mid,hi)

print a[BS(0,len(a)-1)]

我正在使用以下输入尝试您的代码 2 3 4 5 5 8 答案应该是 8 但答案是 5 我正在发布一张包含更多测试用例的图片

我认为你不能运行对未排序的数组进行二进制搜索
该代码还给出了排序数组的大量异常列表

经过优化的变体 - 在大多数情况下快两倍:

# ® Видул Николаев Петров
a = [2, 3, 4, 5, 6, 7, 8, 10, 12, 24, 48, 12, 6, 5, 0, -1]

def calc(a):
    if len(a) <= 2:
        return a[0] if a[0] > a[1]  else a[1]

    l2 = len(a) / 2

    if a[l2 + 1] <= a[l2] and a[l2] >= a[l2 - 1]:
        return a[l2]

    if a[l2] > a[l2 + 1]:
        return calc(a[:l2+1])
    else:
        return calc(a[l2:])

print calc(a) # 48

为什么不用max()方法??

max(lst) 将 return 列表中的最大值