【发布时间】:2015-11-02 23:42:30
【问题描述】:
考虑一个数组 A = [5,1,7,2,3]
所有连续子数组 = { [5], [1], [7], [2], [3], [5,1], [1,7], [7,2], [2,3 ], [5,1,7], [1,7,2], [7,2,3], [5,1,7,2], [1,7,2,3], [5,1,7 ,2,3] }
将上述集合中的所有数组替换为其中的最大元素:
set 看起来像这样:{ [5], [1], [7], [2], [3], [5], [7], [7], [3], [7], [7], [7], [7], [7], [7] }
频率信息:[5] -> 2, [1] -> 1, [7] -> 9, [2] -> 1, [3] -> 2
我的目标是找到上述频率信息。
我的方法:
首先列出一对 (x,y)。 x 是 A 中的元素,它的索引是 y。
列表:[ (5,1), (1,2), (7,3), (2,4), (3,5) ]
按照第一个元素的降序对列表进行排序。现在,
列表:[ (7,3), (5,1), (3,5), (2,4), (1,2) ]
算法:
def f( array, first_index, last_index):
->select an element from LIST starting from left which
is not marked as visited and (first_index <= element.second <=
last_index)
->calculate frequency info of element in tuple as (element.secondvalue-first_index+1) + (element.secondvalue-first_index+1)*(last_index - element.second_value)
->Mark above element as visited
->Recursively solve f( array, first_index,element.secondvalue-1 ),f( array,element.secondvalue+1,last_index)
我们可以轻松设置合适的基本情况。
时间复杂度:O(n*n)
我已经尝试了很多上述算法,但无法提高时间复杂度。我该怎么做?任何提示,方法将不胜感激。
【问题讨论】:
-
好像有一个函数可以描述这种关系
-
相关:this question。我在那里提供的答案将解决您在
O(n)中的问题,而不是O(n log n)作为此问题的其他答案。如果您愿意,我可以在此处以新答案的形式重新发布您问题的相关部分。 -
真的是 O(n) !当然我想知道。请张贴它..
标签: arrays algorithm sub-array