From 97211892492753b1903a882c68b4387051b652cb Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 22 May 2022 00:12:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880042.=E6=8E=A5?= =?UTF-8?q?=E9=9B=A8=E6=B0=B4.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0042.接雨水.md | 85 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index b232ce22..060c0b45 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -744,6 +744,91 @@ var trap = function(height) { }; ``` +### TypeScript + +双指针法: + +```typescript +function trap(height: number[]): number { + const length: number = height.length; + let resVal: number = 0; + for (let i = 0; i < length; i++) { + let leftMaxHeight: number = height[i], + rightMaxHeight: number = height[i]; + let leftIndex: number = i - 1, + rightIndex: number = i + 1; + while (leftIndex >= 0) { + if (height[leftIndex] > leftMaxHeight) + leftMaxHeight = height[leftIndex]; + leftIndex--; + } + while (rightIndex < length) { + if (height[rightIndex] > rightMaxHeight) + rightMaxHeight = height[rightIndex]; + rightIndex++; + } + resVal += Math.min(leftMaxHeight, rightMaxHeight) - height[i]; + } + return resVal; +}; +``` + +动态规划: + +```typescript +function trap(height: number[]): number { + const length: number = height.length; + const leftMaxHeightDp: number[] = [], + rightMaxHeightDp: number[] = []; + leftMaxHeightDp[0] = height[0]; + rightMaxHeightDp[length - 1] = height[length - 1]; + for (let i = 1; i < length; i++) { + leftMaxHeightDp[i] = Math.max(height[i], leftMaxHeightDp[i - 1]); + } + for (let i = length - 2; i >= 0; i--) { + rightMaxHeightDp[i] = Math.max(height[i], rightMaxHeightDp[i + 1]); + } + let resVal: number = 0; + for (let i = 0; i < length; i++) { + resVal += Math.min(leftMaxHeightDp[i], rightMaxHeightDp[i]) - height[i]; + } + return resVal; +}; +``` + +单调栈: + +```typescript +function trap(height: number[]): number { + const length: number = height.length; + const stack: number[] = []; + stack.push(0); + let resVal: number = 0; + for (let i = 1; i < length; i++) { + let top = stack[stack.length - 1]; + if (height[top] > height[i]) { + stack.push(i); + } else if (height[top] === height[i]) { + stack.pop(); + stack.push(i); + } else { + while (stack.length > 0 && height[top] < height[i]) { + let mid = stack.pop(); + if (stack.length > 0) { + let left = stack[stack.length - 1]; + let h = Math.min(height[left], height[i]) - height[mid]; + let w = i - left - 1; + resVal += h * w; + top = stack[stack.length - 1]; + } + } + stack.push(i); + } + } + return resVal; +}; +``` + ### C: 一种更简便的双指针方法: