【发布时间】:2017-01-07 01:24:55
【问题描述】:
我正在学习动态编程的基础知识,并来到 question 寻找数组中的最长递增子序列。在查找 DP 解决方案之前,我决定自己编写代码并提出以下算法,完整代码可以在 here 找到。
想法是创建一个List Array来存储所有递增的子序列,并存储每个子序列对应的最大值以便更快地比较。
private void findLIS(int[] inputArr) {
List[] listOfSubs = new ArrayList[inputArr.length]; //Max different subsequences in an array would be N
//To store the max value of each of the subsequences found yet
List<Integer> maxValList = new ArrayList<Integer>();
listOfSubs[0] = new ArrayList<Integer>();
listOfSubs[0].add(inputArr[0]); //Add the first element of the array to the list
maxValList.add(inputArr[0]);
for (int i=1;i<inputArr.length;i++) {
boolean flag = false;
int iter=0;
//Compare inputArr[i] with the maxVal of each subsequence
for (int j=0; j<maxValList.size(); j++) {
if (inputArr[i]>maxValList.get(j)) {
maxValList.set(j, inputArr[i]); //Update the maxVal in the corresponding position in the list
listOfSubs[j].add(inputArr[i]);
flag = true;
}
iter = j;
}
//If inputArr[i] is not greater than any previous values add it to a new list
if (!flag) {
maxValList.add(inputArr[i]);
listOfSubs[iter+1] = new ArrayList<Integer>();
listOfSubs[iter+1].add(inputArr[i]);
}
}
//Finding the maximum length subsequence among all the subsequences
int max=0, iter=0, index=0;
for (List<Integer> lst : listOfSubs) {
if (lst!=null && lst.size() > max) {
max = lst.size();
index=iter;
}
iter++;
}
//Print the longest increasing subsequence found
System.out.println("The Longest Increasing Subsequence is of length " + listOfSubs[index].size() +
" and is as follows:");
for (int i=0;i<listOfSubs[index].size();i++) {
System.out.print(listOfSubs[index].get(i) + " ");
}
}
代码在 O(n^2) 时间内运行,非常适合中小型输入。但是,当我尝试针对一些在线练习门户(如HackerRank)运行代码时,我得到了 TLE(超出时间限制的错误)和错误答案。我理解 TLE 错误,因为有效的解决方案是 DP O(nlogn) 解决方案,但我对此算法生成的错误答案感到困惑。由于此类情况的输入太大(~10000),我无法手动验证解决方案出错的地方。
可以在here 找到完整的代码以及其中一个数据集的输出。根据 HackerRank 的报告,正确答案应该是 195。
【问题讨论】:
-
离题:n^2 解决方案通过了hackerrank 中的所有测试
-
@Yerken 为什么这是一个离题的问题?它满足 meta.stackexchange.com/questions/129598/… 和 stackoverflow.com/help/mcve 中设置的所有准则。另外,在最后一个链接中,我展示了一个问题可重现的场景。我相信我的解决方案也是 O(n^2) 解决方案?
-
Why is this an off-topic question?我认为它处于临界状态:in 问题中的基本部分应在链接失效时保持独立。您描述了您为解决问题所做的工作,但没有描述结果是什么/为什么解决(应该解决)问题。我至少缺少 WA 输出(20)。 (我对您使用/显示的输出格式感到惊讶。) -
@ShubhamMittal 我并不是说你的问题离题了,我的评论离题了,只是让你知道 n^2 解决方案通过了 Hackerrank 上的所有测试,所以 TLE 可能是由于执行不力
-
@Yerken 道歉!我注意到投票结束了这个问题(题外话)和你的评论,因此很自然地将两者联系起来。
标签: java arrays algorithm dynamic-programming subsequence