[LintCode/LeetCode] Trapping Rain Water [栈和双指针]

本文介绍了一种计算降雨后地形上积水总量的算法。通过栈和双指针两种方法实现,栈法通过寻找相同高度的两侧边界来计算水体积,而双指针法则从两侧峰值开始向中间逼近,以较短一侧计算积水。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

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.
rainwatertrap.png

Example

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

Note

有两种方法。一种是利用Stack去找同一层的两个边,不断累加寄存。如[2, 1, 0, 1, 2],2入栈,1入栈,0入栈,下一个1大于栈顶元素0,则计算此处的雨水量加入res,此过程中0从栈中弹出,1入栈,到下一个2,先弹出1,由于之前还有一个1在栈中,所以计算时高度的因数相减为0,雨水量为0,res无变化,继续pop出栈中的元素,也就是之前的1,此时stack中仍有元素2,说明左边还有边,继续计算底层高度为1,两个值为2的边之间的水量,加入res。
双指针法的思想:先找到左右两边的第一个峰值作为参照位,然后分别向后(向前)每一步增加该位与参照位在这一位的差值,加入sum,直到下一个峰值,再更新为新的参照位。这里有一个需要注意的地方,为什么要先计算左右两个峰值中较小的那个呢?因为在两个指针逼近中间组成最后一个积水区间时,要用较短边计算。

Solution

1. Stack

public class Solution {
    public int trapRainWater(int[] A) {
        Stack<Integer> stack = new Stack<Integer>();
        int res = 0;
        for (int i = 0; i < A.length; i++) {
            if (stack.isEmpty() || A[i] < A[stack.peek()]) stack.push(i);
            else {
                while (!stack.isEmpty() && A[i] > A[stack.peek()]) {
                    int pre = stack.pop();
                    if (!stack.isEmpty()) {
                        res += (Math.min(A[i], A[stack.peek()]) - A[pre]) * (i - stack.peek() - 1);
                    }
                }
                stack.push(i);
            }
        }
        return res;
    }
}

2. Two-Pointer

public class Solution {
    public int trap(int[] A) {
        int left = 0, right = A.length-1, res = 0;
        while (left < right && A[left] < A[left+1]) left++;
        while (left < right && A[right] < A[right-1]) right--;
        while (left < right) {
            int leftmost = A[left], rightmost = A[right];
            if (leftmost < rightmost) {
                while (left < right && A[++left] < leftmost) res += leftmost - A[left];
            }
            else {
                while (left < right && A[--right] < rightmost) res += rightmost - A[right];
            }
        }
        return res;
    }
}
双指针法update: 2018-3
public class Solution {
    public int trap(int[] A) {
        if (A == null || A.length < 3) return 0;
        
        //set left/right pointers
        int l = 0, r = A.length-1;
        
        //find the first left/right peaks as left/right bounds
        while (l < r && A[l] <= A[l+1]) l++;
        while (l < r && A[r] <= A[r-1]) r--;
        
        //output
        int trappedWater = 0;
        
        //implementation
        while (l < r) {
            
            int left = A[l];
            int right = A[r];
             
            //when you have a higher RIGHT bound...
            if (left <= right) {

             //when 'l' is highest left bound
             //it's safe to add trapped water RIGHTward
             while (l < r && left >= A[l+1]) {
                 l++;
                 trappedWater += left - A[l];
             }

             //when left pointer 'l' found 'l+1' a higher left bound
             //reset the left bound
             l++;
            } 

            
            //when you have a higher LEFT bound...
            else {

             //when 'r' is highest right bound
             //it's safe to add trapped water LEFTward
             while (l < r && right >= A[r-1]) {
                 r--;
                 trappedWater += right - A[r];
             }

             //when right pointer 'r' found 'r-1' a higher right bound
             //reset the right bound
             r--;
            }
        }
        
        return trappedWater;
    }
}
资源下载链接为: https://pan.quark.cn/s/22ca96b7bd39 在 IT 领域,文档格式转换是常见需求,尤其在处理多种文件类型时。本文将聚焦于利用 Java 技术,尤其是 Apache POI iTextPDF 库,实现 doc、xls(涵盖 Excel 2003 及 Excel 2007+)以及 txt、图片等格式文件向 PDF 的转换,并实现在线浏览功能。 先从 Apache POI 说起,它是一个强大的 Java 库,专注于处理 Microsoft Office 格式文件,比如 doc xls。Apache POI 提供了 HSSF XSSF 两个 API,其中 HSSF 用于读写老版本的 BIFF8 格式(Excel 97-2003),XSSF 则针对新的 XML 格式(Excel 2007+)。这两个 API 均具备读取写入工作表、单元格、公式、样式等功能。读取 Excel 文件时,可通过创建 HSSFWorkbook 或 XSSFWorkbook 对象来打开相应格式的文件,进而遍历工作簿中的每个 Sheet,获取行列数据。写入 Excel 文件时,创建新的 Workbook 对象,添加 Sheet、Row Cell,即可构建新 Excel 文件。 再看 iTextPDF,它是一个用于生成修改 PDF 文档的 Java 库,拥有丰富的 API。创建 PDF 文档时,借助 Document 对象,可定义页面尺寸、边距等属性来定制 PDF 外观。添加内容方面,可使用 Paragraph、List、Table 等元素将文本、列表表格加入 PDF,图片可通过 Image 类加载插入。iTextPDF 支持多种字体样式,可设置文本颜色、大小、样式等。此外,iTextPDF 的 TextRenderer 类能将 HTML、
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值