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

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

最佳答案

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

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

编辑:

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

关于java - 查找具有两个循环的递增连续子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45244745/

相关文章:

python - 使用 numpy 将 2D 数组中的第 n 列乘以 3D 数组中的第 n 列

java - 是否有将 Scheme/Java/Ruby 代码翻译成英文句子的程序?

java - 从另一个包启动 Activity - 问题

java - 尝试通过数组中的 n 个元素实现圆形旋转后出现奇怪的输出

php - 在发送到 MySQL 之前拆分数组数据

C编程数组赋值问题

java - 带有用于搜索 Web 应用程序的可选字段的 SQL 查询

java - 如何将日期解析为带有 am/pm 的 long 类型?

Java ArrayList.remove() 不工作?

c - 多项式除法