leetcode题集——trapping-rain-water

本文探讨了如何解决LeetCode中的‘trapping-rain-water’问题,通过使用双指针法来计算在给定高度数组中能容纳多少雨水。举例说明,如输入数组[0,1,0,2,1,0,1,3,2,1,2,1],可以捕获6单位的雨水。" 113582857,10294860,西门子PLC位操作与KepServer结合实践,"['PLC编程', 'OPC UA', '西门子编程', '自动化', '数据交互']
摘要由CSDN通过智能技术生成

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.

For example, 
Given[0,1,0,2,1,0,1,3,2,1,2,1], return6.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 

Thanks Marcos for contributing this image!

解析:使用双指针法。分别从数组两边开始遍历,当leftmax>rightmax时,可以求出right=n-2位置的水量;反之,当leftmax<rightmax时,可以求出left=1位置的水量。

循环条件为left<=right。

class Solution {
public:
    int max(int a,int b)
    {
       return a>b?a:b;
    }
    int trap(int A[], int n) 
    {
       if(A==NULL||n<3)
           return 0;
       int sum;
       int leftmax=A[0];
       int rightmax=A[n-1];
       int l=1;
       int r=n-2;
        
      while(l<=r)
      {
        if(leftmax<rightmax)
        {//左侧最小值比右侧值小
           sum+=max(0,leftmax-A[l]); 
           leftmax=max(leftmax,A[l++]);
        }
        else
        {
           sum+=max(0,rightmax-A[r]);
           rightmax=max(rightmax,A[r--]);
        }
              
      }
        return sum;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值