classSolution: deftrap(self, height: List[int]) -> int: stack = [0] ans, n = 0, len(height) for i inrange(1, n): x = height[i] if x < height[stack[-1]]: stack.append(i) continue # 一样的高度取新下表 elif x == height[stack[-1]]: stack.pop() stack.append(i) continue while stack and x > height[stack[-1]]: mid = height[stack.pop()] if stack: ans += (min(height[stack[-1]], x) - mid) * (i - stack[-1] - 1) stack.append(i) return ans
classSolution { public: inttrap(vector<int>& height){ int ans = 0; stack<int> stk; int n = height.size(); for (int i = 0; i < n; ++i) { while (!stk.empty() && height[i] > height[stk.top()]) { int top = stk.top(); stk.pop(); if (stk.empty()) { break; } int left = stk.top(); int currWidth = i - left - 1; int currHeight = min(height[left], height[i]) - height[top]; ans += currWidth * currHeight; } stk.push(i); } return ans; } };