在数组中查找max元素,先升序后降序

2024-09-26 18:05:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)]

Tags: youanlowhichreturnifbshi
3条回答

经过优化的变型-在大多数情况下,速度是原来的两倍:

# ® Видул Николаев Петров
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

我用下面的输入2 3 4 5 5 8来尝试你的代码,答案应该是8但是答案是5我发布了一个图片,里面有几个测试用例enter image description here

我想你不能在未排序的数组上运行二进制搜索
代码还为排序数组提供了大量异常列表

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

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

相关问题 更多 >

    热门问题