1. 程式人生 > 資訊 >索尼 Xperia 5 II 成《穿越火線:槍戰王者》官方賽事比賽用機

索尼 Xperia 5 II 成《穿越火線:槍戰王者》官方賽事比賽用機

技術標籤:LeetCodeleetcode

給定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。
在這裡插入圖片描述
輸入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
輸出:6
解釋:上面是由陣列 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。

解法:

單調棧

class Solution {
public:
    int trap(vector<int>& height) {
        int ans  = 0;
        stack<
int> st; int N = height.size(); for (int i=0; i<N; ++i) { while (!st.empty() && height[i] > height[st.top()]) { int top = st.top(); st.pop(); if (st.empty()) break; int
distance = i - st.top() -1; int bounded_height = min(height[i], height[st.top()]) - height[top]; ans += distance * bounded_height; } st.push(i); } return ans; } };