Problem
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
dp
使用动态规划。题目要求求解-最长递增子序列。子序列说明数字之间不要求必须连续,或者说位置邻接,可以是不同位置的几个数字构成的序列,但是各个数字之间的先后关系不能改变。
动态规划的解法是:首先初始化一个dp数组,dp[i]表示到第i个位置为止(包含第i个元素)的最长递增子序列的长度。那么它的状态转移方程怎么定义?dp[i]应该是从头到第i个元素依次遍历,如果nums[j]小于当前元素numsi,那么dp[i] = dp[j]+1(元素nums[j]再加上当前元素nums[i],因为nums[i]大于nums[j]),每次更新dp[i]时取最大值。最终结果长度取dp[i]的最大值。具体代码如下:
1 | class Solution { |
another
因为题目进一步要求时间复杂度改进到O(nlogn). 这里使用一个辅助数组ends,表示到第i个元素为止的递增子序列。ends数组的维护过程:
- 当前元素nums[i]如果小于end[0],使用nums[i]替换ends[0];
- 当期元素nums[i]大于ends.back(),将当前元素nums[i]存入数组中;
- 否则(当前元素大于数组头,小于数组尾),因为ends数组是一个递增子序列(递增数组),使用二分查找,在ends数组中找到第一个大于等于nums[i]的元素,然后用nums[i]替换掉它
这样,元素遍历完成后,ends数组的长度就是最长递增子序列的长度,因为最长递增子序列不一定只有一个,ends数组最终结果一定是其中的一个解。
不容易想到。
1 | class Solution { |