我的任务是编写一个程序,找到给定数组中最长的递增连续子序列,并打印出该子序列的长度和内容。例如,如果数组为:
int[] arr = {3, 6, 5, 1, 9, 3, 2, 3, 4, 5, 1}
最长的连续递增子序列是2、3、4、5,长度为4。 因此,该方法的输出结果将为:
4
2, 3, 4, 5
这是我的代码,目前为止:
public class LongestSubsequence {
public static void main(String[] args) {
// Test arrays
int[] arrC = {9, 5, 2, 3, 4, 5};
int[] arrA = {1, 2, 3, 4, 5, 7};
int[] arrB = {7, 6, 5, 4, 1, 2};
int[] arr = {3, 6, 5, 1, 9, 3, 2, 3, 4, 5, 1};
longestForward(arr);
}
// input of the int array, returns nothing.
public static void longestForward(int[] arr) {
// variables for Length of longest subsequence found and for the length of the current sequence
int subSeqLength = 1;
int longest = 1;
boolean longestSub = false;
int indexStart = 0;
int indexEnd = 0;
for (int i = 0; i < arr.length-1; i++) {
//Increases subsequence length variable
if (arr[i] < arr[i+1]) {
subSeqLength++;
}
// Sets the current subsequence to the longest variable if it is the longest one found at the time.
else if (subSeqLength > longest) {
longest = subSeqLength;
longestSub = true;
}
// if the current sequence being analyzed is the longest one, keeps track of where it starts and ends
else if (longestSub = true) {
arr[i] = indexStart;
arr[i+1] = indexEnd;
}
// sets the subsequence length back to one if it is no longer increasing
else subSeqLength = 1;
}
System.out.println(subSeqLength);
System.out.println(indexStart);
System.out.print(indexEnd);
}
}
所以我已经找出了如何使程序识别最长子序列的长度。然而,我卡在了如何实际打印它上面。现在,我只是尝试让方法正确地打印最长子序列开始和结束的数组位置。这不是程序所需要的,但我认为在继续打印之前需要弄清楚这一点。
我推断要打印子序列,我需要跟踪最长序列开始和结束的时间,并从那里得到程序在这些元素上打印。但是我的代码似乎并没有正确运行。没有给出错误,它只是运行但没有返回任何东西。
非常感谢任何帮助。谢谢!
subSequence.length
(或其他操作)即可获取其长度。 - user554546longestForward
设为void
类型?为什么不直接在main
函数中打印呢? - user554546