向后搜索数组以寻找最长的连续子序列

时间:2015-02-23 20:40:08

标签: java arrays

这是my previous question的后续问题。

我正在寻找向后搜索的数组中最长的连续序列。

感谢您的帮助。

这是我目前的方法:

 public static void longestBackward(int[] arr)
  {

    int subSeqLength = 1;
    int longest = 1;
    boolean longestSub = false;
    int indexStart = 0;
    int indexEnd = 0;

    for (int i = arr.length-1; i > 0; i--)
    { // We need to check if the current is equal to the previous
        if (arr[i] < arr[i-1])
        {   // if it is we increment the length
            subSeqLength++;
            // Assign the longest to the current subsequence if it's the longest
            if (subSeqLength > longest)
            {
                longest = subSeqLength;
                longestSub = true;
            }
            // We set the new index end if it is the longuest

            if (longestSub)
            {
                indexStart = i + 2 - subSeqLength;
                indexEnd = i + 2;
            }

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

    System.out.println(longest);

    // Print the sequence
    for (int i = indexEnd; i < indexStart; i--)
        System.out.print(arr[i] + ", ");        
  }

2 个答案:

答案 0 :(得分:1)

for (int i = arr.length-1; i >= 0; i--)
    {
        if (arr[i-1] < arr[i - 2])

在第一行中,我可以是0.在第三行中,i-1将为-1,这超出了数组的范围。您可能希望编写i>1或类似内容。

您是否尝试过简单地反转阵列,然后将反转阵列送入原始的工作方法?

答案 1 :(得分:1)

我修改了你的代码并在其中评论了我改变的内容:

public static void longestBackward(int[] arr) {

    int subSeqLength = 1;
    int longest = 1;
    int indexStart = 0;
    int indexEnd = 0;

    /**
     * We iterate while we are higher then 0 not 1 as we retrieve i - 1
     */
    for (int i = arr.length - 1; i > 0; i--) {
        if (arr[i] > arr[i - 1]) {//I've changed < to > remember we are backward. 
            subSeqLength++;

            /*
             * I've removed the longestSub which is useless
            */
            if (subSeqLength > longest) {
                longest = subSeqLength;
                indexStart = i + (subSeqLength - 1); //notice that I modified the bounds
                indexEnd = i - 1;
            }
        } // Else re-initiate the length
        else {
            subSeqLength = 1;
        }
    }

    // Print the sequence
    for (int i = indexStart - 1; i > indexEnd; i--) {
        System.out.print(arr[i] + ", ");
    }
}

如果您不了解某些部分,请务必发表评论。