在数组中找到最长的非连续的非递减子序列

时间:2020-07-06 22:00:26

标签: python arrays algorithm sorting

我想证明为什么要在O(n)中找到大小为n的数组的最长的非连续的非递减子序列。
“查找”是指知道其长度以及相关索引的列表。

Here is a solution in NlogN

Here is the Wikipedia article

我想说服自己,这不可能更快。


这里是部分证明:

为了简单起见,假设O(nlogn)O(n)更快,但这比O(nlogn)更好。

我们可以将两个排序的数组合并为一个由O(n1 + n2)中的所有元素组成的单个排序的数组。

给定一个数组A,我们然后可以在O(n)中找到其最长的最长的非连续的非递减子序列。 如果此序列小于n/2,则对于reversed(A),它大于或等于n/2 [我需要证明]

通过这种方式,我们可以将数组每次按O(n)拆分为已排序的块,并保留大小为k的余数,也可以将其拆分为O(k) + O(remainer)直到剩下一个O(1)元素。

因此,对数组进行排序将需要O(n)

1 个答案:

答案 0 :(得分:0)

Here is a solution in O(n+klogk), where k is the number of elements which are in an unsorted position.

使用上述算法,我们可以使用上述算法O(n+klogk)进行排序,然后遍历未排序和已排序的数组,找到k个元素的索引,从而找出k个元素中哪些不在其位置或更少)的差异(单次通过,O(n))。

其余索引将定义一个排序数组,该数组也是输入数组的不连续子序列,具有最大长度,因为根据定义,这些索引被排序,而其他k

通常,这是O(n log n), but in case there is a need to search for a longest non consecutive subsequence, it would make sense to optimize like this, because the problem will probably be such that n << k`。

相关问题