Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

300. 最长递增子序列 #53

Open
webVueBlog opened this issue Sep 12, 2022 · 0 comments
Open

300. 最长递增子序列 #53

webVueBlog opened this issue Sep 12, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

300. 最长递增子序列

Description

Difficulty: 中等

Related Topics: 数组, 二分查找, 动态规划

给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。

**子序列 **是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。

示例 1:

输入:nums = [10,9,2,5,3,7,101,18]
输出:4
解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。

示例 2:

输入:nums = [0,1,0,3,2,3]
输出:4

示例 3:

输入:nums = [7,7,7,7,7,7,7]
输出:1

提示:

  • 1 <= nums.length <= 2500
  • -104 <= nums[i] <= 104

进阶:

  • 你能将算法的时间复杂度降低到 O(n log(n)) 吗?

Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var lengthOfLIS = function(nums) {
    let dp = new Array(nums.length).fill(1)
    let ans = 0
    for (let i = 0; i < nums.length; i++) {
        // 对于第i个元素nums[i]
        for (let j = 0; j < i; j++) {
            // 遍历i前面的i-1个元素
            if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1)
            // 如果nums[j]比nums[i]小 更新dp[i]
        }
        ans = Math.max(ans, dp[i])
    }
    return ans
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant