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

标签 python arrays binary-search

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

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

最佳答案

优化的变体 - 在大多数情况下速度提高两倍:

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

关于python - 查找数组中的最大元素,先升序再降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424526/

相关文章:

arrays - 查找数组中的局部最小值

javascript - 即使reactjs收到了数据,为什么我的笔记没有显示/更新?

vector 中带有模板的 C++ 结构

arrays - 使用二进制搜索查找最大子数组

python - 在 matplotlib 中旋转(自定义路径)标记时尺寸失真

python - 更新列类型JsonBlob的mysql表行

python - 字典条目都是一样的

python - 给定一个已经创建的python对象,有没有办法通过检查找出构造的实际参数?

javascript - 在javascript数组中显示mysql结果

lisp - 具有更高级别功能的 lisp 中的二进制搜索