public class Solution {
public int lengthOfLIS(int[] nums) {
if(nums==null)
return 0;
int n=nums.length;
int[] asc=new int[n];
int len=0;
for(int i=0;i<n;i++){
int index=Arrays.binarySearch(asc,0,len,nums[i]);
if(index<0)
index=-(index+1);
asc[index]=nums[i];
if(index==len)
len++;
}
return len;
}
}
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is [2, 3, 7, 101]
, therefore the length is
4
. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log
n) time complexity?
分析:新定义一个数组来存储递增的序列。每次新来一个元素时,利用二分搜索在新数组中查找其应该插入的位置,然后更新当前位置的元素,若 该元素的插入位置为当前新数组已有元素大小,则代表当前递增序列又多加了一个元素,则标记递增序列长度的全局变量应该更新。