找到增长最长的连续子序列

时间:2015-02-24 19:37:09

标签: java

我正在尝试编写一个将序列作为数组的程序,然后打印最长的连续子序列及其长度。在我迄今为止编写的代码中(下面),我已经设法在方法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] + ", ");
    }
}
}

2 个答案:

答案 0 :(得分:1)

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

for循环看起来不应该像这样:

for (int i = arr.length - 1; i >= 0; i--) {

你没有得到arr [0]因为你在arr [1]之后停止了。

答案 1 :(得分:0)

只是为了澄清..为什么你不能采取最长的前进和逆转呢?最长的前锋不会是最长落后的逆转吗?