最长递增子序列可以用动态规划的方法,时间复杂度是o(n*n),也可以用二分查找的方法,时间复杂度是o(nlogn)。
首先看二分查找的方法:思路是,顺序插入数据,当插入的数据大于以往的任何值时,插入到最后,若插入的数据不是大于以往的任何值时,首先找到大于要插入数据的一个值,然后,将要插入的数据将该值替换掉。因为找到替换的值的复杂度为o(logn),要进行n次插入,所以时间复杂度是o(nlogn)。
//时间复杂度为O(nlogn)
public static int lis(int[] arr){
int length = arr.length;
int[] temp = new int[length+1];
temp[0] = -1;
int top=0;
int low,mid,high;
for(int i=0;i<length;i++){
if(arr[i]>temp[top]){
temp[++top] = arr[i];
}else{
low = 1;
high = top;
while(low <= high){
mid = (low+high)/2;
if(arr[i] > mid){
low = mid+1;
}else{
high = mid-1;
}
}
temp[low] = arr[i];
}
}
System.out.println(Arrays.toString(temp));
return top;
}
再来看时间复杂度为O(n*n)的动态规划方法:可以参考这篇文章:
http://blog.youkuaiyun.com/lampqiu/article/details/38536637
//时间复杂度为O(n*n)
public static int lis2(int[] arr){
int length = arr.length;
int[] dp = new int[length];
dp[0] = 1;
int max=0;
for(int i = 1;i<arr.length;i++){
for(int j=0;j<i;j++){
if(arr[i] > arr[j] && dp[j]>max){
max = dp[j];
}
}
dp[i] = max+1;
}
int tmp=0;
for(int i=0;i<dp.length;i++){
if(dp[i]>tmp) tmp = dp[i];
}
return tmp;
}