【发布时间】:2019-04-19 11:00:30
【问题描述】:
我试图在 O(nlogn) 的数组中寻找最长的递减子序列。不确定这是否真的需要 O(nlogn),但无论如何这会返回最长递增子序列的长度,而不是最长递减子序列的长度。谁能帮忙?!?
def binary_search(L, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (L[m] >= key):
r = m
else:
l = m
return r
def LongestDecreasingSubsequenceLength(L, size):
tailTable = [0 for i in range(size + 1)]
len = 0
tailTable[0] = L[0]
len = 1
for i in range(1, size):
if (L[i] < tailTable[0]):
# new smallest value
tailTable[0] = L[i]
elif (L[i] > tailTable[len-1]):
tailTable[len] = L[i]
len+= 1
else:
tailTable[binary_search(tailTable, -1, len-1, L[i])] = L[i]
return len
L = [ 38, 20, 15, 30, 90, 14, 6, 7]
n = len(L)
print("Length of Longest Decreasing Subsequence is ",
LongestDecreasingSubsequenceLength(L, n))
【问题讨论】:
-
我不明白“最长递减子序列”?不会遍历列表一次,如果下一个较小则增加,如果下一个较大则存储更简单?
-
在大多数情况下,这意味着某些测试的顺序错误
标签: python algorithm subsequence