【发布时间】:2017-12-10 08:15:36
【问题描述】:
问题陈述:目的是在nlogn时间内找到最长的递增子序列(不连续)。
算法:我理解这里解释的算法: http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/.
我不明白的是在下面的代码中,tail 中存储了什么。
int LongestIncreasingSubsequenceLength(std::vector<int> &v) {
if (v.size() == 0)
return 0;
std::vector<int> tail(v.size(), 0);
int length = 1; // always points empty slot in tail
tail[0] = v[0];
for (size_t i = 1; i < v.size(); i++) {
if (v[i] < tail[0])
// new smallest value
tail[0] = v[i];
else if (v[i] > tail[length-1])
// v[i] extends largest subsequence
tail[length++] = v[i];
else
// v[i] will become end candidate of an existing subsequence or
// Throw away larger elements in all LIS, to make room for upcoming grater elements than v[i]
// (and also, v[i] would have already appeared in one of LIS, identify the location and replace it)
tail[CeilIndex(tail, -1, length-1, v[i])] = v[i];
}
return length;
}
例如,如果输入是 {2,5,3,,11,8,10,13,6}, 该代码给出了正确的长度为 6。 但是tail会存储2,3,6,8,10,13。
所以我想了解tail中存储了什么?这将有助于我理解这个算法的正确性。
【问题讨论】:
标签: algorithm sorting binary-search correctness