leetcode 42 接雨水

解题思路

想出来的方法有点笨,只打败了5%的人。。
主要思路是从两侧开始遍历,一层一层的累计。
当两侧均不为0时,计算这一层中的告诉<=0的柱子的数量,然后加到结果中,然后将每一个柱子的高度都减1;直到数组中大于0的数字的数量不超过2的时候停止遍历。、
这样做会遍历数组很多次,所以效率很低,想一下优化的方法、

代码

class Solution {
    int cnt = 0;
    public int trap(int[] arr) {
        if(arr==null || arr.length<=2)
            return 0;
        int n = arr.length;
        for(int num : arr)
            if(num>0)
                cnt++;
        // System.out.println("cnt->"+cnt);
        int res = 0;
        while(cnt>=2){
            res += helper(arr);
        }
        return res;
        
    }
    
    public int helper(int[] arr){
        int left = 0;
        int right = arr.length-1;
        int res = 0;
        while(arr[left]<=0)
            left++;
        while(arr[right]<=0)
            right--;
        while(left<=right){
            if(arr[left]<=0)
                res++;
            if(arr[left]==1)
                cnt--;
            arr[left]--;
            left++;
        }
        // System.out.println("cnt->"+cnt);
        // System.out.println("arr->"+Arrays.toString(arr));
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值