簡體   English   中英

查找數組中的最大元素,先升序再降序

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

我嘗試了一個在線挑戰,其中有一個問題如下:

你得到一個數組,它首先增加然后開始減少。 例如: 2 3 4 5 6 7 8 6 4 2 0 -2 找到這些數組的最大元素。

以下是我使用二進制搜索的代碼,它在 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

我正在使用以下輸入 2 3 4 5 5 8 嘗試您的代碼,答案應該是8但答案是5我正在發布帶有更多測試用例的圖像在此處輸入圖片說明

我認為你不能在未排序的數組上運行二進制搜索
該代碼還為排序數組提供了大量異常列表

你為什么不使用max()方法?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM