题目
给定一个无序的整数数组,找到其中最长上升子序列的长度。leetcode.cn/problems/lo…
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。
输入:nums = [10,9,2,5,3,7,101,18]
输出:4
解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
官方答案
看如下代码
const lengthOfLIS = (nums) => {
let dp = Array(nums.length).fill(1);
let result = 1;
for(let i = 1; i < nums.length; i++) {
for(let j = 0; j < i; j++) {
if(nums[i] > nums[j]) {//当nums[i] > nums[j],则构成一个上升对
dp[i] = Math.max(dp[i], dp[j]+1);//更新dp[i]
}
}
result = Math.max(result, dp[i]);//更新结果
}
return result;
};
let l = lengthOfLIS(nums)
console.log('------------')
console.log(l)
参考资料
思路
1.错误的思路:
- 双层遍历数组。
- 对于内层遍历的数组部分,要组成一个升序,所以就要有判断当前一个和下一个数组元素的大小。然后组成一个新的递增数组。
- 最后返回最长的数组。
2.错误的思路
- 双层遍历数组。
- 每次拿数组的最后一个元素和之前所有的数据一一比大小。只要最后一个元素比前面的数据大,计数器就加1。
- 返回最大值。
自己错误的代码(错误代码)
// let nums = [10,9,2,5,3,7,101,18];
let nums = [0,1,0,3,2,3]; // 这个测试用例 fn 函数有问题
function fn(nums) {
let maxIndex = 0,
arr = [];
for(let i = 0; i < nums.length; i++) {
let tem = [];
for(let j = i; j < nums.length; j++) {
let item = nums[j];
if(i == j) {
tem.push(item);
}
if(tem[tem.length - 1] < item) {
tem.push(item);
}
}
if( maxIndex <= tem.length ) {
arr = tem;
maxIndex = tem.length;
}
}
return maxIndex;
}
let c = fn(nums);
console.log(c);