標籤:col images lse har 技術分享 mos HERE example tle
題目:接雨水
難度:hard
題目內容:
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.
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!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]Output: 6
翻譯:簡單翻譯下就是,給出每一格木塊的數量,最後求得這些木塊放在一起時能接住多少雨水。
我的思路:此題和第11題很像:Container With Most Water,但是11題裡是豎線,這裡是方塊,而且那是尋求所接水最多的,這裡是求所能接住的所有水,不過取水的思想可以參考一下,就是利用雙指標,同向移動。每次移動兩邊比較矮的那一個。
然而,因為考慮到要減去方體的體積,我還是不會做這個。
答案代碼:
1 public int trap(int[] height) { 2 if (height.length == 0) return 0; 3 int left = 0; 4 int right = height.length - 1; 5 int area = 0, leftHeight = height[0], rightHeight = height[height.length - 1]; 6 while (left < right){ 7 if (height[left] < height[right]){ 8 left++; 9 leftHeight = Math.max(leftHeight, height[left]);10 area += leftHeight - height[left];11 }12 else{13 right--;14 rightHeight = Math.max(rightHeight, height[right]);15 area += rightHeight - height[right];16 }17 }18 return area;19 }
答案複雜度:O(N)
答案思路:果然,是利用了雙指標,每次移動比較矮的那一邊,然後取此時最高的高度。
然後!
如果當前高度比最高的高度要矮,那麼儲水的量就肯定要加上之間的這個差值。
(因為此時是比矮的那一邊的最高高度還要矮,所以這個差值的水是必定能接住的)
舉個例子:(以【】代替方塊,___代表0個方塊)
【】
【】 【】
【】_________【】【】
A B C
首先因為A比C高,所以移動C那邊的指標right,right移動到B點,然後取 high[right] (B)與 之前的最高高度 C 比較,得到還是C高,而因為這邊是矮的遲早對面會比這個高,所以此時儲水量就應該加上(C-B)。
而如果當前移動後就是最高的高度,那麼儲水量則不增加。
所以最後每次移動後,儲水量應該加上 ( 此方最高高度 - 當前高度 ),對應代碼: area += leftHeight - height[left];
LeetCode第[42]題(Java):Trapping Rain Water