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?
经典的DP入门题目,温习一下。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
vector<int> maxLength(nums.size(), 1);
for (int i = 1; i < nums.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (nums[i] > nums[j]) {
maxLength[i] = max(maxLength[i], maxLength[j] + 1);
}
}
}
return *max_element(maxLength.begin(), maxLength.end());
}
};
O(nlogn)解法,记录LIS最大值中的最小可能取值,用二分查找。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
vector<int> maxVals(nums.size(), 0);
maxVals[0] = nums[0];
int lis = 1;
for (int i = 1; i < nums.size(); ++i) {
int low = 0;
int up = lis - 1;
while (low <= up) {
int mid = (low + up) / 2;
if (maxVals[mid] < nums[i]) {
low = mid + 1;
}
else {
up = mid - 1;
}
}
maxVals[low] = nums[i];
if (low >= lis) {
++lis;
}
}
return lis;
}
};