From f7bfc0536a2d2b094101e6394a6f7150971a89f6 Mon Sep 17 00:00:00 2001 From: Qi Jia <13632059+jackeyjia@users.noreply.github.com> Date: Tue, 13 Jul 2021 19:00:19 -0700 Subject: [PATCH] add js solution for lengthOfLIS --- problems/0300.最长上升子序列.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index 8b4ad5b1..9a7c543b 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -170,6 +170,25 @@ func lengthOfLIS(nums []int ) int { return len(dp) } ``` + +Javascript +```javascript +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]) { + dp[i] = Math.max(dp[i], dp[j]+1); + } + } + result = Math.max(result, dp[i]); + } + + return result; +}; +``` *复杂度分析* - 时间复杂度:O(nlogn)。数组 nums 的长度为 n,我们依次用数组中的元素去更新 dp 数组,相当于插入最后递增的元素,而更新 dp 数组时需要进行 O(logn) 的二分搜索,所以总时间复杂度为 O(nlogn)。 - 空间复杂度:O(n),需要额外使用长度为 n 的 dp 数组。