LeetCode-Trapping Rain Water
又是这种需要仔细考虑的题目,
很容易就会漏掉一些情况,哎,感冒了,
完全不在状态,调了好几个小时,
写代码的能力实在是不行,总感觉写出来的代码不够优雅,
1 class Solution { 2 public: 3 int trap(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int res = 0; 7 if (A == NULL) { 8 return res; 9 } 10 int i = 1; 11 int b = 0; 12 int low; 13 while (i < n && A[i] >= A[i - 1]) { 14 b = i; 15 ++i; 16 } 17 while (i < n) { 18 while (i < n && A[i] < A[i - 1]) { 19 ++i; 20 } 21 int k = i - 1; 22 int j = k - 1; 23 low = A[k]; 24 while (i < n && A[i] >= A[i - 1]) { 25 if (A[i] > A[i - 1]) { 26 if (j >= b) { 27 while (j >= b && A[i] >= A[j]) { 28 int len = i - j - 1; 29 int h = A[j] - low; 30 low = A[j]; 31 res += len * h; 32 while (j >= b && A[j] <= low) 33 --j; 34 } 35 if (j >= b) { 36 int len = i - j - 1; 37 int h = A[i] - low; 38 low = A[i]; 39 res += len * h; 40 } 41 } 42 ++i; 43 continue; 44 } 45 ++i; 46 } 47 if (A[b] <= A[i - 1]) { 48 b = i - 1; 49 } 50 ++i; 51 } 52 return res; 53 } 54 };
大神们的方法,超级简单,找左右两边的最大值即可;
1 class Solution { 2 public: 3 int trap(int A[], int n) { 4 if (n == 0) return 0; 5 int left[n]; 6 int right[n]; 7 8 int lmax = A[0]; 9 for (int i = 0; i < n; ++i) 10 { 11 lmax = max(lmax, A[i]); 12 left[i] = lmax; 13 } 14 15 int rmax = A[n-1]; 16 for (int i = n - 1; i >= 0; --i) 17 { 18 rmax = max(rmax, A[i]); 19 right[i] = rmax; 20 } 21 22 int res = 0; 23 for (int i = 0; i < n; ++i) 24 res += min(left[i], right[i]) - A[i]; 25 26 return res; 27 } 28 };