我的任務是編寫一個程序,該程序在給定的數組中找到最長的連續子序列,並打印該子序列的長度以及它自身的子序列。 說陣列是:查找數組中最長的連續子序列
int[] arr = {3, 6, 5, 1, 9, 3, 2, 3, 4, 5, 1}
最長連續遞增子爲2,3,4,5的4 長度所以該方法的輸出將是
4
2, 3, 4, 5
這是我的代碼到目前爲止:
public class LongestSubsequence {
public static void main(String[] args) {
// Test arrays
int[] arrC = {9, 5, 2, 3, 4, 5};
int[] arrA = {1, 2, 3, 4, 5, 7};
int[] arrB = {7, 6, 5, 4, 1, 2};
int[] arr = {3, 6, 5, 1, 9, 3, 2, 3, 4, 5, 1};
longestForward(arr);
}
// input of the int array, returns nothing.
public static void longestForward(int[] arr) {
// variables for Length of longest subsequence found and for the length of the current sequence
int subSeqLength = 1;
int longest = 1;
boolean longestSub = false;
int indexStart = 0;
int indexEnd = 0;
for (int i = 0; i < arr.length-1; i++) {
//Increases subsequence length variable
if (arr[i] < arr[i+1]) {
subSeqLength++;
}
// Sets the current subsequence to the longest variable if it is the longest one found at the time.
else if (subSeqLength > longest) {
longest = subSeqLength;
longestSub = true;
}
// if the current sequence being analyzed is the longest one, keeps track of where it starts and ends
else if (longestSub = true) {
arr[i] = indexStart;
arr[i+1] = indexEnd;
}
// sets the subsequence length back to one if it is no longer increasing
else subSeqLength = 1;
}
System.out.println(subSeqLength);
System.out.println(indexStart);
System.out.print(indexEnd);
}
}
所以我想通了如何讓程序識別最長的子序列的長度。但是,我堅持要如何才能真正將它打印出來。現在,我只是試圖讓方法正確地打印出陣列中最長的子序列開始和結束的地方。這不是程序中需要的,但我認爲在開始打印之前我需要弄清楚這一點。
我推斷,爲了打印子序列,我需要跟蹤最長序列何時開始和結束,並從那裏獲得打印在這些元素上的程序。但我的代碼似乎沒有正確運行。沒有給出的錯誤,它只是運行,但不返回任何東西。
任何幫助,非常感謝。謝謝!
答案爲什麼不只是創建一個返回的最長連續子序列(或如果超過一個最大長度連續子存在一個這樣子)的功能?然後,你可以執行'subSequence.length'(或其他)來獲得它的長度。 – 2015-02-23 17:53:49
只是實現相同事情的另一種方式。看看你是否有任何提示:http://www.sanfoundry.com/java-program-implement-longest-arithmetic-progression-algorithm/ – CKing 2015-02-23 17:55:07
我不確定你的意思是「創建一個函數」。你的意思是創建一個幫助器方法,返回正確的數組並將其傳遞給我的longestForward方法,然後將其傳遞給我的主方法?如果是這樣,我會怎麼做呢?我已經嘗試了很多代碼迭代來追蹤我想要的內容,但我無法弄清楚。我可以開始嗎? – Zephyr 2015-02-23 17:59:00