單調棧 42 接雨水

2021-10-02 10:14:47 字數 971 閱讀 5692

給定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。

上面是由陣列 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。 感謝 marcos 貢獻此圖。

示例:輸入: [0,1,0,2,1,0,1,3,2,1,2,1]

輸出: 6

class solution 

int length = index - s.top() - 1;

result += (min(height[index], height[s.top()]) - height[currentindex]) * length;

}s.push(index++);

}return result;

}};

class solution:

def trap(self, height: list[int]) -> int:

result = 0

currentindex = 0

stack = list()

while(currentindex < len(height)):

while(len(stack) != 0 and height[currentindex] > height[stack[-1]]):

index = stack[-1]

stack.pop()

if len(stack) == 0:

break

length = currentindex - stack[-1] - 1

result += length * (min(height[currentindex],height[stack[-1]]) - height[index])

currentindex += 1

return result

leetcode 42 接雨水 單調棧

接雨水 給定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。上面是由陣列 0,1,0,2,1,0,1,3,2,1,2,1 表示的高度圖,在這種情況下,可以接 6 個單位的雨水 藍色部分表示雨水 感謝 marcos 貢獻此圖。示例 輸入 0,1,0,2,1...

Leetcode 42 接雨水(棧解)

題目描述 定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。上面是由陣列 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 ...

leetcode42 接雨水 棧實現

public static int trap int height stackstack new stack 對陣列中每乙個元素遍歷 for int i 0 i height.length 1 i 取出的last和左右兩面牆的最低求差 x math.min height stack.peek hei...