[英]sorted on basis of two keys, descending order sort for first and ascending for second
[英]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
你為什么不使用max()
方法?
max(lst)
將返回列表中的最大值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.