题目描述
给定数组arr,设长度为n,输出arr的最长递增子序列。(如果有多个答案,请输出其中字典序最小的)
示例1
输入
[2,1,5,3,6,4,8,9,7]
返回值
[1,3,4,8,9]
示例2
输入
[1,2,8,6,4]
返回值
[1,2,4]
代码如下:
import java.util.*;
public class Solution {
/**
* retrun the longest increasing subsequence
* @param arr int整型一维数组 the array
* @return int整型一维数组
*/
public int[] LIS (int[] arr) {
// write code here
int len = arr.length;
int maxLen[] = new int[len];
int value[] = new int[len];
maxLen[0] = 1;
value[0] = arr[0];
int index=0;
for(int i=1;i<len;i++){
if(arr[i] > value[index]){
value[++index] = arr[i];
maxLen[i] = index+1;
}else{
int k = serchBinary(value,index,arr[i]);
value[k]=arr[i];
maxLen[i]=k+1;
}
}
int[] newArr=new int[index+1];
for (int i = arr.length - 1; i >= 0; i--) {
if(maxLen[i]==index+1){
newArr[index]=arr[i];
index--;
}
}
return newArr;
}
public static int serchBinary(int arr[],int len,int value){
int low=0,high=len;
while (true){
if(low>high) {
return low;
}
int mid = low + (high-low)/2;
if(arr[mid]<value){
low=mid+1;
}else if(arr[mid]>value){
high=mid-1;
}else {
return mid;
}
}
}
}