最大连续递增子列【Java】数据结构算法,简明算法
用java实现,但c和python.其他语言都是一个道理
不用定义新的表,只需要原序列(表),再定义三个新的变量用于保存数据直接上代码,详细注释代码里有
如果不需要输出最大子序列只需要输出最大子序列的长度,把最后的输出删除即可
例如:
输入:15
1 9 2 5 7 3 4 6 8 0 11 15 17 17 10
输出:3 4 6 8
public class MaximalIncreasingSubsequence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 初试化线性表---
System.out.print("线性表的长度");
int length = scanner.nextInt();
ArrayList<Integer> arrayList = new ArrayList<Integer>(length);
for (int i = 0; i <length; i++) {
System.out.print("第"+ (i+1) +"个元素:");
arrayList.add(scanner.nextInt());
}
// 最大递增数组的起始位置和递增位数
int MaxPosition = 0;
int MaxLength = 0;
// 计算当前数组的长度
int CurrentLength = 0;
for (int i = 0; i < arrayList.size()-1; i++) {
if (arrayList.get(i) < arrayList.get(i+1)){
CurrentLength++;
}
else {
// 将当前递增数组长度重置
CurrentLength = 0;
}
// 判断当前递增数组是否为最大递增数组
if (CurrentLength > MaxLength){
// 将当前递增数组的开始位置赋给MaxPosition [注]要加上1才能保证位置相同
MaxPosition = i - CurrentLength + 1;
// 将最大数组长度赋给MaxLength
MaxLength = CurrentLength;
}
}
// 输出最大子序列的开始位置和长度
System.out.print("最大数组开始位置:" + MaxPosition);
System.out.println(" "+"最大数组长度:" + MaxLength+1);
// 输出最大数组
for (int i = 0; i <= MaxLength; i++) {
System.out.println(arrayList.get(MaxPosition));
MaxPosition++;
}
}
}
如果有什么bug请指正==。==