inttrap(vector<int>& height){ int res = 0, pre = 0; stack<int> st; for (int i = 0; i < height.size(); i++) { if (height[i] >= pre) { while (!st.empty()) { res += pre - st.top(); st.pop(); } pre = height[i]; st.push(pre); continue; } if (height[i] <= st.top()) { st.push(height[i]); continue; } int tmp = 1; while (st.top() < height[i]) { res += height[i] - st.top(); st.pop(); tmp++; } for (int j = 0; j < tmp; j++) st.push(height[i]); } return res; }
优化:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
inttrap(vector<int>& height){ int res = 0; stack<int> st; for (int i = 0; i < height.size(); i++) { while (!st.empty() && height[i] > height[st.top()]) { int mid = st.top(); st.pop(); if (st.empty()) break; int left = st.top(); int curWidth = i - left - 1; int curHeight = min(height[left], height[i]) - height[mid]; res += curWidth * curHeight; } st.push(i); } return res; }