如何递归搜索列表中的最大值

时间:2018-11-03 09:11:42

标签: python algorithm

我对python和算法非常陌生,遇到一个定义如下的问题:

假设您获得了一个l大小的python列表n,其中仅包含数字。我们将l从0索引到n-1。此外,我们假设存在一个索引k ∈ {1, ..., n-2}使得

  • 对于所有i ∈ {0, ..., k-1}l[i] < l[i+1]
  • 对于所有i ∈ {k, ..., n-2}l[i] > l[i+1]

换句话说,l是单峰的。以下是一个k=3的示例:

  

l = [-5,8,12, 15 ,13,12,10,5,1,0,-2]

我可以使用迭代方法轻松实现它:

def findK(l):
    k = 0
    while l[k] < l[k + 1]:
        k += 1
    return k

但是我该如何使用 O(logn) 的递归方法呢?

4 个答案:

答案 0 :(得分:4)

通过使用三元搜索

的概念可以获得单峰函数的最大值/最小值
    mDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override


        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            Log.d("", "onChildChanged:" + dataSnapshot.getKey());
            sections.clear();



             childList.clear();
            for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {

                AlaramData    alaramData =  postSnapshot.getValue(AlaramData.class);
               int x = 0;
                // here you can access to name property like university.name
                childList.add(alaramData);
            }


            Log.d("", "Value is: " + childList);
            //Create a List of Section DataModel implements Section

            sections.add(new SectionHeader(childList, "2018", 1));
            adapterRecycler.notifyDataChanged(sections);

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w("", "Failed to read value.", error.toException());
        }
    });

解决方案的总体复杂度为O(log 3 N)。您可以从https://www.hackerearth.com/practice/algorithms/searching/ternary-search/tutorial/https://en.wikipedia.org/wiki/Ternary_search

了解更多信息

答案 1 :(得分:1)

算法

  • 您可以使用二进制搜索来执行此操作。
  • 如果我们遇到b-1 < b < b+1b是我们中间元素的模式,那么肯定是最高元素在数组的右边。
  • 如果我们遇到b-1 > b > b+1b是我们中间元素的模式,那么肯定是最高元素在数组的左侧。
  • 如果我们遇到b-1 < b > b+1b是我们中间元素的模式,那么这个b是我们的答案。

代码:

mid = 0,low=0,high = arr.size-1
while low <= high: 
    mid = low + (high - low) / 2
    if arr[mid] > arr[mid-1] && arr[mid] > arr[mid + 1]:
        return arr[mid]
    else if arr[mid] < arr[mid-1] && arr[mid] > arr[mid + 1]:
        high = mid - 1
    else 
        low = mid + 1

时间复杂度为 O(log 2 n)。但是,正如@nellex在其answer中提到的那样,三元搜索提供了更好的性能。

答案 2 :(得分:0)

您的代码的递归版本为

def max_modal(list, start=0):
    If start < len(list):
        If list[start]>list[start+1]:
            Return list[start]
        Else:
            Return max_modal(list,start=start+1)
     Else:
         Return list[start]

但是在解释器语言中,此Schild比迭代方式要慢得多

答案 3 :(得分:-1)

查找列表最大值的经典方法是

def max(list):
     k=INT_MIN
     For x in list:
          K=max(k,x)
      Return k 

那将是O(n)