postgis 怎樣的方式存入資料_空間資料庫的細節:PostGIS Extension
阿新 • • 發佈:2021-02-09
給定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。
示例 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 個單位的雨水(藍色部分表示雨水)。
示例 2:
輸入:height = [4,2,0,3,2,5]
輸出:9
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/trapping-rain-water
思路:
題解參考:單調棧O(n)解決
if(height.length == 0 || height.length < 3) {
return 0;
}
int ans = 0;
Deque<Integer> stack = new ArrayDeque<>();
for(int i=0;i<height.length;i++) {
while (!stack.isEmpty() && height[stack.peek()] < height[i]) {
int cur = stack.pop();
// 如果有相同高度的出棧,直到找到大於此高度的索引
while(!stack.isEmpty() && height[stack.peek()] == height[cur]) {
stack.pop();
}
// 如果棧是空了,說明左邊沒有大於該索引高度的值
if(!stack.isEmpty()) {
int leftHeight = height[stack.peek()];
int rightHeight = height[i];
ans += (Math.min(leftHeight,rightHeight) - height[cur]) * (i-stack.peek()-1);
}
}
stack.push(i);
}
return ans;
}