42. 接雨水
給定?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
提示:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
先看我的代碼:
class Solution {
public:int trap(vector<int>& height) {int len=height.size();auto Maxheight=max_element(height.begin(),height.end());int maxheight=*Maxheight;int num=0;for(int i=1;i<=maxheight;i++){vector<int> a;int id=-1;for(int j=0;j<len;j++){if(height[j]>=i){a.push_back(j);id++;if(id>0)num+=a[id]-a[id-1]-1;}}}return num;}
};
有一個小缺陷,不能通過所有的測試案例:
只有4個測試案例沒有通過,說明我的思路是正確的,但是沒有考慮到時間復雜度,說沒有考慮也不對,我剛開始寫出的代碼是這樣的:
class Solution {
public:int trap(vector<int>& height) {int len=height.size();auto Maxheight=max_element(height.begin(),height.end());int maxheight=*Maxheight;int num=0;for(int i=1;i<=maxheight;i++){vector<int> a;for(int j=0;j<len;j++){if(height[j]>=i)a.push_back(j);}int Si=a.size();if(Si>=2){for(int h=0;h<Si-1;h++){num+=a[h+1]-a[h]-1;}}}return num;}
};
顯然,這樣時間復雜度更大。
下面 是標準答案:
class Solution {
public:int trap(vector<int>& height) {int n=height.size();if(n==0){return 0;}vector<int>leftMax(n);leftMax[0]=height[0];for(int i=1;i<n;i++){leftMax[i]=max(leftMax[i-1],height[i]);}vector<int>rightMax(n);rightMax[n-1]=height[n-1];for(int i=n-2;i>=0;i--){rightMax[i]=max(rightMax[i+1],height[i]);}int ans=0;for(int i=0;i<n;i++){ans+=min(leftMax[i],rightMax[i])-height[i];}return ans;}
};
?