Java 查找具有两个循环的递增连续子序列

Java 查找具有两个循环的递增连续子序列,java,arrays,Java,Arrays,我试图在输入数组中找到最长的连续子序列。我当前的代码有一个外部循环,从输入的每个索引开始一个序列,还有一个内部循环,循环遍历起始索引之后的所有元素。我知道这可以通过简单地设置开始和结束索引并复制数组范围来解决,但我不明白为什么这段代码不能识别从一个元素到另一个元素的减少。当我运行程序时,它仍然打印整个输入数组 import java.util.Arrays; public class LongestSubsequence { public static void longestForwar

我试图在输入数组中找到最长的连续子序列。我当前的代码有一个外部循环,从输入的每个索引开始一个序列,还有一个内部循环,循环遍历起始索引之后的所有元素。我知道这可以通过简单地设置开始和结束索引并复制数组范围来解决,但我不明白为什么这段代码不能识别从一个元素到另一个元素的减少。当我运行程序时,它仍然打印整个输入数组

import java.util.Arrays;

public class LongestSubsequence {

 public static void longestForward(int[] input) {
   int length = 1; 
   int longest = 1;
   int[] currentSubsequence = new int[input.length];
   int[] longestSubsequence = new int[input.length];

   //Two loops: outer loop iterates through elements of the array 
   //and makes each one the starting index before executing inner loop
   for (int i = 0; i < input.length-1; i++) {
     currentSubsequence[i] = input[i];

     //next loop iterates through all proceeding elements in the array 
     //after the starting index
     for (int j = i + 1; j < input.length; j++) { 
       //if the next element is greater than the previous element in the 
       // subsequence array, it is appended to the array
       if(input[j] > currentSubsequence[j-1]) {
         currentSubsequence[j] = input[j];
         length++;
       }
       //otherwise the length of the subsequence is compared to the 
       //longest so far, if it is bigger it sets the longest subsequence
       //to the current subsequence
       else if(input[j] < currentSubsequence[j-1]) {
         if(length > longest) {
           longest =length;
           longestSubsequence = currentSubsequence;
         }
       }
     }
   }
   int[] finalArray = Arrays.copyOfRange(longestSubsequence, 0, length);
   System.out.println(Arrays.toString(finalArray));
 }

  public static void main (String[] args) {
    int[] x = {1, 2, 3, 2, 6};
    longestForward(x);
  }
}

您忘记重置当前长度变量:

else if(input[j] < currentSubsequence[j-1]){
    if(length > longest){
        longest =length;
        longestSubsequence = currentSubsequence;
    }
    length = 1; // Add this
}    
编辑:


我刚刚意识到这并不能解决整个问题,我认为您需要获取最长序列的起始索引,并在副本中使用它。

请缩进您的代码。这是很难遵循,因为它是现在哇这么简单的修复…不敢相信我错过了!就起始索引而言,是否有办法避免这种情况,而是在每次循环后重置currentSubsequence数组?