這題放上來是因為自己第一回見到這種題,覺得它好玩兒 =)
Trapping Rain Water
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!
class Solution { public: int trap(int A[], int n) { } };
題目不難,觀察下就可以發現被水填滿后的形狀是先升后降的塔形,因此,先遍歷一遍找到塔頂,然后分別從兩邊開始,往塔頂所在位置遍歷,水位只會增高不會減小,且一直和最近遇到的最大高度持平,這樣知道了實時水位,就可以邊遍歷邊計算面積。
從看題目開始一共十分鍾,算本菜鳥在AC率二字打頭的題目中至今最快的一次。。
class Solution { public: int trap(int A[], int n) { if(n <= 2) return 0; int max = -1, maxInd = 0; int i = 0; for(; i < n; ++i){ if(A[i] > max){ max = A[i]; maxInd = i; } } int area = 0, root = A[0]; for(i = 0; i < maxInd; ++i){ if(root < A[i]) root = A[i]; else area += (root - A[i]); } for(i = n-1, root = A[n-1]; i > maxInd; --i){ if(root < A[i]) root = A[i]; else area += (root - A[i]); } return area; } };
總結:
這道題和LeetCode上 "Candy" 一題都采用了定義兩個指針向中部某一點靠攏的做法(當然Candy還有更快的解,見以前的這篇),這也算是小技巧之一吧,在需要時要能第一時間想到。