LeetCode-42 Trapping Rain Water

本文介绍了一种从数组两端向内遍历的方法来计算数组中可容纳的水量,通过比较相邻元素并更新最大高度来实现最优解。

题目:求一个数组序列所能容纳的水的体积

思路:从两端向中间逼近

class Solution {
public:
    int trap(int A[], int n) {
        if(n==0)return 0;
        
        int result=0;
        int i,j;
        int head=0;
        int tail=n-1;
            while(head<tail){
                while(A[head]<=A[head+1]&&head<tail)head++;
                while(A[tail]<=A[tail-1]&&tail>head)tail--;
                int temp;
                if(head<tail){
                if(A[head]<=A[tail]){
                    temp=A[head];
                    head++;
                    while(A[head]<temp&&head<tail){
                        result+=temp-A[head];
                        head++;
                    }
        
                }
                else{
                    temp=A[tail];
                    tail--;
                    while(A[tail]<temp&&tail>head){
                        result+=temp-A[tail];
                        tail--;
                    }
                    
                }
                
            }  
            }
       return result; 
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值