From d77a99bf75ca7033ae3d5357408b566a2c1f1c9b Mon Sep 17 00:00:00 2001 From: nn Date: Thu, 18 Sep 2025 21:15:28 +0800 Subject: [PATCH] =?UTF-8?q?20250918=E7=AC=AC=E4=B8=80=E5=91=A8=E7=BB=83?= =?UTF-8?q?=E4=B9=A0=E9=A2=98=E6=8E=A5=E9=9B=A8=E6=B0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ..._\351\203\221\344\275\263\345\250\234.cpp" | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 "topic01/submit/LC0042_\351\203\221\344\275\263\345\250\234.cpp" diff --git "a/topic01/submit/LC0042_\351\203\221\344\275\263\345\250\234.cpp" "b/topic01/submit/LC0042_\351\203\221\344\275\263\345\250\234.cpp" new file mode 100644 index 0000000..a072f48 --- /dev/null +++ "b/topic01/submit/LC0042_\351\203\221\344\275\263\345\250\234.cpp" @@ -0,0 +1,35 @@ +#include +#include +using namespace std; + +class Solution { +public: + int trap(vector& height) { + if (height.empty()) return 0; + + stack st; // 单调栈,存储柱子的索引,保持栈内元素对应高度递减 + int water = 0; // 接雨水总量 + + for (int i = 0; i < height.size(); ++i) { + // 当栈不为空且当前柱子高度大于栈顶柱子高度时,可能形成积水 + while (!st.empty() && height[i] > height[st.top()]) { + int bottom = st.top(); // 凹槽底部的索引 + st.pop(); + + if (st.empty()) break; // 没有左边界,无法形成积水 + + int left = st.top(); // 左边界索引 + int width = i - left - 1; // 凹槽宽度 + // 积水高度 = 左右边界的最小高度 - 凹槽底部高度 + int height_diff = min(height[left], height[i]) - height[bottom]; + + water += width * height_diff; // 累加积水面积 + } + st.push(i); // 当前柱子索引入栈 + } + + return water; + } +}; + + -- Gitee