题目:
对于一个数字序列,请设计一个复杂度为O(nlogn)的算法,返回该序列的最长上升子序列的长度,这里的子序列定义为这样一个序列U1,U2...,其中Ui < Ui+1,且A[Ui] < A[Ui+1]。
给定一个数字序列A及序列的长度n,请返回最长上升子序列的长度。
public int findLongest(int[] A, int n) {
// write code here
/*
解题思路:采用动态规划,dp[i]表示到第i个数,包含的最长的子序列;
对于dp[i]的计算,依次遍历0到i-1个数,找到最大的dp[j]
*/
int[] dp=new int[n];
dp[0]=1;
for(int i=1;i<n;i++){
int temp=1;
for(int j=i;j>=0;j--){
if(A[i]>A[j]){
if(temp<dp[j]+1){//如果第j个元素比第i个元素小
temp=dp[j]+1;
}
}
}
dp[i]=temp;
}
Arrays.sort(dp);
return dp[n-1];
}