LeetcodeLongest Increasing Subsequence
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeLongest Increasing Subsequence相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/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?
思路:
1、简单动态规划,c[i]表示从0~i的数组中 包含nums[i]的LIS,状态转移方程:c[i]=max{c[j]+1} ,j<i且nums[i]>nums[j],时间复杂度为O(n^2)
2、动态规划加二分搜索,b[i]表示长度为i的LIS最后一个元素大小,end是b数组最后一个元素也就是当前LIS的下标。 对每个元素进行如下判断:
若nums[i]>b[end],则更新LIS,否则二分搜索b数组比nums[i]元素大的最小位置idx,此时b[idx]>nums[i]>b[idx-1] 更新idx位置,因为此时同样长度的子串,包含nums[i]的要比包含b[idx]要小。 时间复杂度O(nlogn)。
算法:
1、