通过两个循环查找增加的连续子序列

时间:2017-07-21 18:46:44

标签: java arrays

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

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);
  }
}

1 个答案:

答案 0 :(得分:1)

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

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

编辑:

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