注意这个递增子序列是连续的,所以可以用O(n)的算法来实现。
保存一个全局的最大值,然后在扫描数组过程中更新。
public class LIS {
//index is the beginning index of longest contiguous increasing sequence
public static int index;
//to calculate the longest contiguous increasing sequence
public static int length(int[] A,int size){
if(size<=0)return 0;
int res=1;
int current=1;
for(int i=1;i<size;i++){
if(A[i]>A[i-1]){
current++;
}
else{
if(current>res){
index=i-current;
res=current;
}
current=1;
}
}
return res;
}
public static void main(String[] args){
int []A={2,13,6,8,9,1};
System.out.println(length(A,6));
System.out.println(LIS.index);
}
}
问题2:从输入的数字字符串中找最长连续递增子序列的长度,若有多个长度相同的最长递增子序列,取大小最大的那个。
比如有个递增子序列是5678,另一个递增子序列是5679,比较这两个数的大小即可
分析:把该字符串的每个元素提取到一个整数数组中,接下来的解决方案便同上个问题相同。
public class Test2 {
public static int index;
public static int max=0;
public static int longestlen(int[] A,int size){
if(size<=0)return 0;
max=A[0];
int res=1;
String str="";
int current=1;
for(int i=1;i<size;i++){
if(A[i]>A[i-1]){
current++;
}
else{
//A[i]<=A[i-1]
//the last index in increasing sequence is i-1
if(current>res){
index=i-current;
res=current;
for(int j=0;j<current;j++){
str+=Integer.toString(A[i-current+j]);
}
max=Integer.parseInt(str);
}
else if(current==res){
for(int j=0;j<current;j++){
str+=Integer.toString(A[i-current+j]);
}
int l_max=Integer.parseInt(str);
if(l_max>max){
max=l_max;
index=i-current;
}
}
current=1;
str="";
}
}
return res;
}
public static int LIS(String str){
if(str==null)return 0;
int [] A=new int[str.length()];
for(int i=0;i<str.length();i++)
//A[i]=Integer.parseInt(str.charAt(i)+"");
A[i]=Integer.parseInt(str.substring(i, i+1));
return longestlen(A,str.length());
}
public static void main(String[] args){
System.out.println(LIS(new String("345673578925678")));
System.out.println(index);
System.out.println(max);
}
}
本文介绍了一种O(n)的算法,用于寻找数组中最长的连续递增子序列,并提供了一个扩展应用案例,即从数字字符串中找到最长且数值最大的连续递增子序列。

1025

被折叠的 条评论
为什么被折叠?



