给定一个由 N 个整数组成的序列。如何找到形成排列的相邻数字的最长子序列的长度。我只找到了 O(N^2) 算法。我认为应该有 O(NlogN) 甚至 O(N) 的解决方案。请建议其中任何一个。
这个序列的答案1 3 1 2 5
是 3 (4 1 3 1 2 5 )
这是 SPOJ 问题LPERMUT。
O(N^2) 算法
Foreach i find the sum of first i elemetns: Sum(i)
Foreach i find the last element with indexes 1 .. i-1 which is equal to i-rd element: Prev(i)
Foreach i iterate j throw i+1 .. N while Prev(j) equals between i and j.
//So we get that all elemnent between i and j are distinct.
Then check if sum of them is equal to 1+2+...(j-i+1).
If it occurs that elements are permutation.
Sum of the elements between i and j we can get by Sum(j) - Sum(i-1)