From afcf6cd5a1093c3bc4f525b211858da02e4c47c6 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 19 May 2022 15:03:09 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880718.=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E9=87=8D=E5=A4=8D=E5=AD=90=E6=95=B0=E7=BB=84.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0718.最长重复子数组.md | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index 87b1492a..0b7b5199 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -297,6 +297,56 @@ const findLength = (nums1, nums2) => { } ``` +TypeScript: + +> 动态规划: + +```typescript +function findLength(nums1: number[], nums2: number[]): number { + /** + dp[i][j]:nums[i-1]和nums[j-1]结尾,最长重复子数组的长度 + */ + const length1: number = nums1.length, + length2: number = nums2.length; + const dp: number[][] = new Array(length1 + 1).fill(0) + .map(_ => new Array(length2 + 1).fill(0)); + let resMax: number = 0; + for (let i = 1; i <= length1; i++) { + for (let j = 1; j <= length2; j++) { + if (nums1[i - 1] === nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + resMax = Math.max(resMax, dp[i][j]); + } + } + } + return resMax; +}; +``` + +> 滚动数组: + +```typescript +function findLength(nums1: number[], nums2: number[]): number { + const length1: number = nums1.length, + length2: number = nums2.length; + const dp: number[] = new Array(length1 + 1).fill(0); + let resMax: number = 0; + for (let i = 1; i <= length1; i++) { + for (let j = length2; j >= 1; j--) { + if (nums1[i - 1] === nums2[j - 1]) { + dp[j] = dp[j - 1] + 1; + resMax = Math.max(resMax, dp[j]); + } else { + dp[j] = 0; + } + } + } + return resMax; +}; +``` + + + -----------------------