Longest Increasing Subsequence
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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
n^2解法:
动规典型算法:LIS(最长增长子序列),时间复杂度n^2。
c++ code:
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = nums.size();
int dp[len];
for(int i=0;i<len;i++) {
int tmax = 1;
for(int j=0;j<i;j++) {
if(nums[j] < nums[i]) {
tmax = tmax > dp[j]+1 ? tmax : dp[j]+1;
}
}
dp[i] = tmax;
}
int ans = 0;
for(int i=0;i<len;i++) {
ans = dp[i] > ans ? dp[i] : ans;
}
return ans;
}
};
nlogn解法:
动规 + 二分查找,时间复杂度nlogn。
分析:
示例:nums = 9,2,3,7,8,4,5,6
num=9 -> dp=9
num=2 -> dp=2
num=3 -> dp=2,3
num=7 -> dp=2,3,7
num=8 -> dp=2,3,7,8
num=4 -> dp=2,3,4,8
num=5 -> dp=2,3,4,5
num=6 -> dp=2,3,4,5,6
java code:
public class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
int lenLIS = 0;
for(int num:nums) {
int index = Arrays.binarySearch(dp,0,lenLIS,num);
if(index < 0) // index < 0,表示无此元素,index = -(insertion point) - 1。具体可查看binarySearch API
index = -(index + 1);
dp[index] = num;
if(lenLIS == index) lenLIS++; // 此时的num是dp中最大值
}
return lenLIS;
}
}