gpt4 book ai didi

java - 寻找最长的递增连续子序列

转载 作者:行者123 更新时间:2023-12-01 11:52:21 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序将序列作为数组,然后打印最长的连续子序列及其长度。在我迄今为止编写的代码中(如下),我已经成功地在方法longestForward 中完成了这一任务。然而,在作业规范中,我还被要求编写另一种方法,longestBackwards,它完成完全相同的任务,即。将打印完全相同的内容,但它必须向后搜索原始数组。这就是我遇到困难的地方。

我设法编写了一个方法,仅以相反的顺序打印最长连续子序列的最后两个成员(例如,对于数组 4, 5, 6,它打印 6, 5)。但是它确实正确打印了长度。

如果有人能帮助找出我做错了什么,我将不胜感激。

import java.util.Scanner;
public class LongestSubsequence {
public static void main(String[] args) {

// Test array
int[] arr = {4, 5, 6};


longestForward(arr);
longestBackward(arr);

}

public static void longestForward(int[] arr)
{
int subSeqLength = 1;
int longest = 1;
int indexStart = 0;
int indexEnd = 0;

for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] < arr[i + 1] )//We need to check if the current is equal to the next
{
subSeqLength++;//if it is we increment
if (subSeqLength > longest)//we assign the longest and new bounds
{
longest = subSeqLength;
indexStart = i + 2 - subSeqLength;
indexEnd = i + 2;
}

}
else
subSeqLength = 1;//else re-initiate the straight length
}

System.out.println(longest);
for (int i = indexStart; i < indexEnd; i++)//print the sequence

System.out.print(arr[i] + ", ");
}
public static void longestBackward(int[] arr) {

int subSeqLength = 1;
int longest = 1;
int indexStart = 0;
int indexEnd = 0;
for (int i = arr.length - 1; i > 0; i--) {
if (arr[i] > arr[i - 1]) {
subSeqLength++;
if (subSeqLength > longest) {
longest = subSeqLength;
indexStart = i + (subSeqLength - 1);
indexEnd = i - 1;
}
} // Else re-initiate the length
else {
subSeqLength = 1;
}
}
System.out.println("");
// Print the sequence
System.out.println(longest);
for (int i = indexStart-1; i > indexEnd; i--) {
System.out.print(arr[i] + ", ");
}
}
}

最佳答案

只是为了澄清一下..为什么你不能将最长的向前和反向它?最长的前进不是最长的后退的反转吗?

关于java - 寻找最长的递增连续子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28704714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com