【发布时间】:2023-03-27 21:01:01
【问题描述】:
我有一个返回子序列长度的函数,但我还需要返回子序列本身,但我无法让它工作。
我已经尝试了以下代码,但子序列只有在它是最长的第一个子序列时才能正确返回。
如果我使用以下数组,10 的长度是正确的,但它返回的子序列不正确 [1, 2, 3, 4, 10, 11, 12, 13, 14, 15]
int n = arr.length;
HashSet<Integer> S = new HashSet<Integer>();
HashSet<Integer> Seq = new HashSet<Integer>();
int ans = 0;
// Hash all the array elements
for (int i = 0; i < n; i++) {
S.add(arr[i]);
}
System.out.println(S);
// check each possible sequence from the start
// then update optimal length
for (int i = 0; i < n; ++i)
{
System.out.println("ARR " + i);
// if current element is the starting
// element of a sequence
if (!S.contains(arr[i]-1))
{
//System.out.println("INSIDE .CONTAINS");
// Then check for next elements in the
// sequence
int j = arr[i];
int t = 0;
while (S.contains(j)) {
System.out.println("ANS " + ans);
t++;
if (t > ans ) { Seq.add(j);}
j++;
// System.out.println("T " + t);
// System.out.println("SEQ <<<<<<< " + Seq );
}
// update optimal length if this length
// is more
if (ans < j-arr[i]) {
ans = j-arr[i];
}
}
}
System.out.println(Seq);
System.out.println(ans);
return ans;
【问题讨论】:
-
您在问题中说
return乘以,但您的代码中没有一条return语句。我猜你的意思是打印/输出。 -
你试过调试了吗?你的发现在哪里?
-
@MrSmith42 如果我使用以下数组 { 4, 1, 2, 6, 7, 8, 3, 10, 11, 12, 13, 15, 14, 9 }。我得到了正确的长度为10,但子序列输出为[1, 2, 3, 4, 10, 11, 12, 13, 14, 15]
标签: java algorithm subsequence