300. 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?
My Solution(C/C++)
#include
#include
#include
using namespace std;
class Solution {
public:
int lengthOfLIS(vector &nums) {
if (nums.size() == 0) {
return 0;
}
vector dp(nums.size());
int result = 1;
for (int i = 0; i < nums.size(); i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j] && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
}
}
if (dp[i] > result) {
result = dp[i];
}
}
return result;
}
};
int main() {
vector nums;
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
nums.push_back(3);
nums.push_back(1);
nums.push_back(4);
Solution s;
printf("最长上升子序列的长度为:%d", s.lengthOfLIS(nums));
return 0;
}
结果
最长上升子序列的长度为:4
My Solution2.0(C/C++)
class Solution {
public:
int lengthOfLIS(vector &nums) {
if (nums.size() == 0) {
return 0;
}
vector stack;
for (int i = 0; i < nums.size(); i++) {
if (stack.empty() || stack.back() < nums[i]) {
stack.push_back(nums[i]);
}
else {
for (int j = 0; j < stack.size(); j++) {
if (stack[j] >= nums[i]) { //与栈中元素相等时也要替换,不然栈中可能会同时存入多个相同元素
stack[j] = nums[i];
break;
}
}
}
}
return stack.size();
}
};
My Solution2.0plus(C/C++, n*logn)
class Solution {
public:
int lengthOfLIS(vector &nums) {
if (nums.size() == 0) {
return 0;
}
vector stack;
for (int i = 0; i < nums.size(); i++) {
if (stack.empty() || stack.back() < nums[i]) {
stack.push_back(nums[i]);
}
else {
int k = getKthOfStack(stack, nums[i]);
stack[k] = nums[i];
}
}
return stack.size();
}
private:
int getKthOfStack(vector &stack, int num) {
int begin = 0;
int end = stack.size() - 1;
int mid, index;
while (begin <= end) {
mid = (begin + end) / 2;
if (num == stack[mid]) {
return mid;
}
else if (num < stack[mid]) {
end = mid - 1;
if (mid == 0 || num > stack[mid - 1]) {
index = mid;
}
}
else if (num > stack[mid]) {
begin = mid + 1;
if (mid == stack.size() - 1 || num < stack[mid + 1]) {
index = mid + 1;
}
}
}
return index;
}
My Solution(Python)
class Solution:
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
max_dp, result = 0, 1
dp = [[nums[i]] for i in range(len(nums))]
dp[0].append(1)
for i in range(1, len(nums)):
for j in range(i):
if dp[i][0] > dp[j][0]:
max_dp = max(max_dp, dp[j][1])
dp[i].append(max_dp + 1)
result = max(result, max_dp + 1)
max_dp = 0
return result