题目描述

原题链接

个人解法

Javascript

Java

  1. class Solution {
  2. public int trap(int[] height) {
  3. int len = height.length, sum = 0, left = 0, right = 0,flag=0;
  4. for (int i = 1; i <len-1;i++){
  5. for (int j=i-1;j>=0;j--){
  6. left=Math.max(left,height[j]);
  7. }
  8. for (int j=i+1;j<len;j++){
  9. right=Math.max(right,height[j]);
  10. }
  11. left=Math.min(right,left);
  12. if (left>height[i]){
  13. sum+=(left-height[i]);
  14. }
  15. left=0;
  16. right=0;
  17. }
  18. return sum;
  19. }
  20. }

其他解法

Java

动态规划

  1. public int trap(int[] height) {
  2. int sum = 0;
  3. int[] max_left = new int[height.length];
  4. int[] max_right = new int[height.length];
  5. for (int i = 1; i < height.length - 1; i++) {
  6. max_left[i] = Math.max(max_left[i - 1], height[i - 1]);
  7. }
  8. for (int i = height.length - 2; i >= 0; i--) {
  9. max_right[i] = Math.max(max_right[i + 1], height[i + 1]);
  10. }
  11. for (int i = 1; i < height.length - 1; i++) {
  12. int min = Math.min(max_left[i], max_right[i]);
  13. if (min > height[i]) {
  14. sum = sum + (min - height[i]);
  15. }
  16. }
  17. return sum;
  18. }

Javascript