简体   繁体   English

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

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

I tried an online challenge which had a question as follows:我尝试了一个在线挑战,其中有一个问题如下:

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 .例如: 2 3 4 5 6 7 8 6 4 2 0 -2 Find the maximum element of these array.找到这些数组的最大元素。

Following is my code using binary search and it gives correct answer in O(log(n)) but I don't know whether there is a better solution or not.以下是我使用二进制搜索的代码,它在 O(log(n)) 中给出了正确答案,但我不知道是否有更好的解决方案。 Can anyone help me with that?任何人都可以帮助我吗?

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

An optimised variant - twice faster in most cases:优化的变体 - 在大多数情况下快两倍:

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

i am trying your code with the following input 2 3 4 5 5 8 and the answer should be 8 but the answer is 5 i am posting an image with a few more test cases我正在使用以下输入 2 3 4 5 5 8 尝试您的代码,答案应该是8但答案是5我正在发布带有更多测试用例的图像在此处输入图片说明

i think u cannot run binary search on an unsorted array我认为你不能在未排序的数组上运行二进制搜索
the code also gives huge list of exceptions for sorted arrays该代码还为排序数组提供了大量异常列表

Why don't you use the max() method??你为什么不使用max()方法?

max(lst) will return the max value in a list max(lst)将返回列表中的最大值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM