Description
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 length 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?
Solution
给一个未排序的整数数组,找到长度最长的递增子序列。
可以采用n次DP在O(n^2)解决。follow up 采用更巧妙的策略,O(nlogn)时间解决。
1.DP solution
For each integer in nums, we could perform a iteration to calculate how many intergers are smaller than it. And for the number smaller than it, if its dp[] value is greater than others, dp[I] = dp[j] + 1; After that, use another iteration in dp[] to get the longest one which is the answer.
dp[] is initialized all by 1.
2.Count tails.
Let tails[length - 1] as the smallest number when the subsequence is size big. It is obvious that tails is sorted in ascend way. So we could use binary insert to arrange numbers to tails[].
For each number in numbers, perform binary search in tails. If number is bigger than the last one in tails[](left == size), size should plus one; if not, find right place for num in tails[], update tails[left] value for binary search. Finally, return size of tails[] is the answer.
Code
- DP solution
class Solution {
public int lengthOfLIS(int[] nums) {
if (nums.length <= 1){
return nums.length;
}
int[] dp = new int[nums.length];
Arrays.fill(dp,1);
for (int i = 1; i < nums.length; i++){
for (int j = 0; j < i; j++){
if (nums[j] < nums[i]){
if (dp[j] + 1 > dp[i]){
dp[i] = dp[j] + 1;
}
}
}
}
int max = Integer.MIN_VALUE;
for (int i : dp){
if (i > max){
max = i;
}
}
return max;
}
}
- Count tails
class Solution {
public int lengthOfLIS(int[] nums) {
int[] tails = new int[nums.length];
int size = 0;
for (int num : nums){
int left = 0, right = size;
while (left != right){
int middle = left + (right - left) / 2;
if (tails[middle] < num){
left = middle + 1;
}
else{
right = middle;
}
}
tails[left] = num;
if (left == size) size++;
}
return size;
}
}
Time Complexity: O(n^2) O(nlogn)
Space Complexity: O(n)
Review
Count tails solution is excellent. I can not figure out by myself.