Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #352

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

Merged
pull merged 4 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Sep 28, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
添加 0042.接雨水 Go版本的单调栈压缩版解法
  • Loading branch information
ShuangmingMa authored Sep 16, 2023
commit 8c3f0649271a343ea103f829daf9a75c47db2825
39 changes: 39 additions & 0 deletions problems/0042.接雨水.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,45 @@ func min(x, y int) int {
}
```

单调栈压缩版:

```go
func trap(height []int) int {
stack := make([]int, 0)
res := 0

// 无需事先将第一个柱子的坐标入栈,因为它会在该for循环的最后入栈
for i := 0; i < len(height); i ++ {
// 满足栈不为空并且当前柱子高度大于栈顶对应的柱子高度的情况时
for len(stack) > 0 && height[stack[len(stack) - 1]] < height[i] {
// 获得凹槽高度
mid := height[stack[len(stack) - 1]]
// 凹槽坐标出栈
stack = stack[: len(stack) - 1]

// 如果栈不为空则此时栈顶元素为左侧柱子坐标
if len(stack) > 0 {
// 求得雨水高度
h := min(height[i], height[stack[len(stack) - 1]]) - mid
// 求得雨水宽度
w := i - stack[len(stack) - 1] - 1
res += h * w
}
}
// 如果栈为空或者当前柱子高度小于等于栈顶对应的柱子高度时入栈
stack = append(stack, i)
}
return res
}

func min(x, y int) int {
if x < y {
return x
}
return y
}
```

### JavaScript:

```javascript
Expand Down

AltStyle によって変換されたページ (->オリジナル) /