Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input:
[10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the ength is 4.
Note:
- 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?
思路:自己想了一个思路,不过时间和空间都比较落后。
申请一个和nums[ ]数组等长的数组sequence[],用来记录当前坐标往后能组成自增序列的长度。
以[10,9,2,5,3,7,101,18]为例,数组长度为8,申请数组sequence[8];
从末尾向前遍历,
nums[7]=18,18除了自身后面没有更大的数,所以sequence[7]=1;
nums[6]=101, 101除了自身后面没有更大的数,所以sequence[6]=1;
nums[5]=7, 7后面有101比自身大,且sequence[6]=1,所以sequence[5]=sequence[6]+1=2。因为101和18最长序列都是1,所以忽略18;
nums[4]=3,3后面有7比自身大,且sequence[5]=2,所以sequence[4]=sequence[5]+1=3。因为101和18最长序列都是1,小于7的最长序列,所以忽略;
nums[3]=5,5后面有7比自身大,sequence[5]=2,所以sequence[4]=sequence[5]+1=3。因为7的最长子序列是2,等于3的最长序列,所以忽略;
nums[2]=2,2后面有5比自身大,sequence[3]=3;所以sequence[2]=sequence[3]+1=4。因为3的最长序列都是2,等于5的最长序列,所以忽略;
num[0]=10、num[1]=9,后面只有101和18比自身大,所以sequence[0]=sequence[1]=sequence[6]+1=2;
最后返回sequence数组中最大的值即为最长的子序列。
代码:
class Solution {
public int lengthOfLIS(int[] nums) {
int maxLength = 0;
int length = nums.length;
if(length<=0)
return 0 ;
if(length ==1)
return 1;
int[] sequenceNum = new int[length];
sequenceNum[length-1]=1;
for(int i=length-2;i>=0;i--)
{
sequenceNum[i]=1;
for(int j=i+1;j<length;j++)
{
if(nums[i] < nums[j] && sequenceNum[i] <= sequenceNum[j])
{
sequenceNum[i] = sequenceNum[j]+1;
}
}
maxLength = Math.max(maxLength,sequenceNum[i]);
}
return maxLength;
}
}