2015-02-23 23 views
2

這是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] + ", ");   
    } 

回答

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] + ", "); 
    } 
} 

請確認您發表評論,如果有它的某些部分,你不明白。

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

在第一行中,i可爲0。在三,I-1將是-1,這是出界的數組。你可能想寫i>1或類似的。

您是否嘗試過簡單地顛倒數組,然後將反轉的數組輸入到原始的工作方法中?

+0

該任務說我不允許顛倒數組。我必須向後分析。 – Zephyr 2015-02-23 20:44:40

+0

另外,我看到了這個錯誤。謝謝!但是,即使改變它以確保它不爲零,我仍然會出現超出界限的錯誤。 – Zephyr 2015-02-23 20:45:18

+0

仔細查看發生錯誤的行。錯誤會給你行號。 – 2015-02-23 20:51:42