Given an array nums of integers, find the length of the longest strictly increasing subsequence in it.
A subsequence is a sequence derived from an array that removes (or does not remove) elements from the array without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1 :
input : nums = [10,9,2,5,3,7,101,18]
output : 4
explains : The longest increasing subsequence is [2,3,7,101], so the length is 4.
Example 2 :
input : nums = [0,1,0,3,2,3]
output : 4
Example 3 :
input : nums = [7,7,7,7,7,7,7]
output : 1
Problem solving ideas
The conventional method is to use dynamic programming, time complexity O(n^2)
.
class Solution {
public int lengthOfLIS(int[] nums) {
// 定义 dp 数组
// dp[i] 表示以 nums[i] 这个数结尾的最长递增子序列长度
int[] dp = new int[nums.length];
// 初始值填充 1(子序列至少包含当前元素自己)
Arrays.fill(dp, 1);
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
// 假设 dp[0...i-1] 都已知,需要求出 dp[i]
// 只需要遍历 nums[0...i-1],找到结尾比 nums[i] 小的子序列 dp[j]
// 然后把 nums[i] 接到最后,就可以形成一个新的递增子序列,长度为 dp[j] + 1
// 显然,可能形成很多种新的子序列,只需要选择最长的,作为 dp[i] 的值即可
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
// 遍历 dp 数组,找出最大值
int res = 0;
for (int i = 0; i < dp.length; i++) {
res = Math.max(res, dp[i]);
}
return res;
}
}
The idea of DOM diff in Vue is adopted here, namely greedy method . It should be noted that the final length of stack
is correct, but the content may not be correct. Since two layers of loop traversal are used, the time complexity is O(n^2)
.
var lengthOfLIS = function (nums) {
let stack = [];
for (let i = 0; i < nums.length; i++) {
// 数组为空直接入栈,不为空则获取栈顶元素判断大小
if (stack.length == 0 || getTopEle(stack) < nums[i]) {
stack.push(nums[i]);
} else {
let index = findNextEle(stack, nums[i]);
stack[index] = nums[i];
}
}
return stack.length;
};
function getTopEle(arr) {
if (!arr.length) return 0;
return arr[arr.length - 1];
}
function findNextEle(arr, n) {
// 判断大小用 >= ,即不替换栈顶元素
return arr.findIndex(item => item >= n);
}
For further optimization, the findIndex
method can be replaced by binary search, and the time complexity is reduced to O(nlogn)
.
refer to
Intensive reading of "The Longest Ascending Subsequence of DOM diff"
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。