標籤:else dex res http stack image var alt nbsp
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
思路1:
這個題可以逐層掃描,每一次減掉最低的非0高度。但是這個的問題是如果說height裡大於0且distinct的數有m個,就loop m次。 很容易就逾時了。
具體code如下:
public int Trap(int[] height) { int res = 0; int count =0; foreach(var h in height) count+= h; while(count>1) { int j =0; while(height[j] == 0) { j++; } int trap = j; int a = 0; int minTrap = height[j]; for(int i =j+1;i< height.Count();i++) { if(height[i] !=0) { minTrap = Math.Min(minTrap,height[i]); a += Math.Max(0,i-trap-1); trap = i; } } res += a*minTrap; for(int i =0;i< height.Count();i++) { if(height[i]>0) { count-=minTrap; height[i] -=minTrap; } } } return res; }
解法2:
每一個slot的位置,它能儲水的量為其左邊最高高度與右邊最高高度的最小值與其本身高度的差,舉個例子,如果在i=5的位置,i左邊最高位置為9, 右邊最高位置為7, 那這個地方能儲水的量就是Math.Min(9,7) - 5 = 2. 所以我們設定一個dp數組,dp[i]記錄i位置左側最高高度,左遍曆一遍;再設定一個dp數組,dp[i]記錄i位置右側最高高度,右遍曆一遍;然後再loop一遍即可算出大小。
code如下:
public int Trap(int[] height) { int res = 0; int size = height.Count(); var leftMax = new int[size]; var rightMax = new int[size]; for(int i =1;i< size;i++) { leftMax[i] = Math.Max(height[i-1],leftMax[i-1]); } for(int i =size-2;i>=0;i--) { rightMax[i] = Math.Max(height[i+1], rightMax[i+1]); } for(int i =1;i< size-1;i++) { int min = Math.Min(leftMax[i],rightMax[i]); if(height[i]<min) { res += min-height[i]; } } return res; }
解法3:
我們也可以用stack,這個就是比較慢,stack壓入的是比stack.Peek()小的值,這樣每一個0都會被壓進去。計算的時候當height[i]大於stack.Peek時候,就需要先pop一個值出來,這個是底,然後再用stack.Peek()與height[i]的最小值, 減掉底,然後乘以index的差。這個地方因為
public int Trap(int[] height) { int max =0; int res = 0; int size = height.Count(); if(size <= 2) return res; int i =0; var stack = new Stack<int>();//store the largerst heigth index while(i< size) { if(stack.Count()==0 || height[i] <= height[stack.Peek()]) stack.Push(i++); else { int bot = stack.Pop(); res += (stack.Count()==0)?0:((Math.Min(height[stack.Peek()], height[i]) - height[bot])*(i - stack.Peek()-1));; } } return res; }
42. Trapping Rain Water