leetcode - Trapping Rain Water
2013-11-06 09:50 张汉生 阅读(170) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 int trap(int A[], int n) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 int * lr = new int [n]; 7 int last = 0; 8 for (int i=0; i<n; i++){ 9 if (A[i]<last) 10 lr[i]=last-A[i]; 11 else{ 12 lr[i] = 0; 13 last = A[i]; 14 } 15 } 16 int * rl = new int [n]; 17 last = 0; 18 for (int i=n-1; i>=0; i--){ 19 if (A[i]<last) 20 rl[i]=last-A[i]; 21 else{ 22 rl[i] = 0; 23 last = A[i]; 24 } 25 } 26 int sum = 0; 27 for (int i=0; i<n; i++) 28 sum += lr[i]<rl[i]?lr[i]:rl[i]; 29 delete []lr; 30 delete []rl; 31 return sum; 32 } 33 };