0
点赞
收藏
分享

微信扫一扫

Day25 接雨水

给定n个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水

https://leetcode-cn.com/problems/trapping-rain-water/

示例1:

示例2:

提示:

Java解法

package sj.shimmer.algorithm.ten_3;

/**
 * Created by SJ on 2021/2/18.
 */

class D25 {
    public static void main(String[] args) {
        System.out.println(trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));
        System.out.println(trap(new int[]{4, 2, 3}));
    }

    public static int trap(int[] height) {
        int result = 0;
        if (height != null && height.length != 1) {
            int left = 0;
            int temp = 0;
            boolean hasLeft = false;
            int length = height.length;
            for (int i = left; i < length; i++) {
                if (!hasLeft) {
                    if (height[i] != 0) {
                        left = i;
                        hasLeft = true;
                    }
                } else {
                    if (height[i] >= height[left]) {
                        result += temp;
                        temp = 0;
                        left = i;
                    } else {
                        temp += height[left] - height[i];
                        if (i == length - 1) {
                            temp = 0;
                            int right = length - 1;
                            //当前left是最长的柱子,进行逆向求取
                            for (int j = length - 1; j > left; j--) {
                                if (height[right] == 0) {
                                    right = j;
                                    continue;
                                }
                                if (height[j] >= height[right]) {
                                    result += temp;
                                    temp = 0;
                                    right = j;
                                } else {
                                    temp += height[right] - height[j];
                                    if (j == left + 1) {
                                        return result + temp;
                                    }
                                }
                            }
                        }


                    }
                }
            }
        }
        return result;
    }
}

官方解

https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/

  1. 暴力

    • 时间复杂度: O(n^2)
    • 空间复杂度: O(1)
  2. 动态编程

    • 时间复杂度: O(n)
    • 空间复杂度: O(n)
  3. 栈的应用

    • 时间复杂度: O(n)
    • 空间复杂度: O(n);最坏情况下
  4. 双指针

    • 时间复杂度: O(n)
    • 空间复杂度: O(1)
举报

相关推荐

0 条评论