leetcode-trapping rain water

这是第一种方法:
/*maintain two pointers, think of it has real live water..
fill the container from two sides
how the water will be kept*/
public class Solution {
    public int trap(int[] A) {
        int len=A.length;
        int min=0,v=0;
        if(len<3)return 0;
        int left=0,right=len-1;
        min=Math.min(A[left],A[right]);
        while(left<right){
            while(left<right&&A[left]<=min){  //find the left edge
                v+=(min-A[left]);
                left++;
            }
            while(right>left&&A[right]<=min){ //find the right edge
                v+=(min-A[right]);
                right--;
            }
            min=Math.min(A[left],A[right]);
        }
        return v;
    }
}


第二中方法:

Trapping rain water的最naive的方法:onepass

没有注意到的问题:

1一个container的两端应该是取最小的高度。

2在找第一个容器的左端的时候没有注意到数组的下标的界限的问题!注意当数组的下标有变化的时候一定紧跟着不要忘记对其范围进行限制。

3解题思路是:先找到第一个容器的最左端的点,然后用一个函数去找这个容器的右端,这个右端或者是大于等于这个容器的左端,或者是找右侧的最大值。如果这个值是左边的第一个点,那么重新从下一个元素开始重新找。

/*The idea is that maintain two pointers, and a function to return the next pointer*/
public class Solution {
    public int trap(int[] A) {
        int len = A.length,v=0;
        if(len<3)return 0;
        int slow=0;
        //find the first pointer
        while((A[slow]==0||(A[slow]<=A[slow+1]))){
            slow++;
            if(slow==len-1)return v;
        }
        
        while(slow<len-2){
            int[] next=findPointer(A[slow],slow+1,A,len);
            if(next[0]==0)return v;
            if(next[0]==slow+1){
                slow=slow+1;
                continue;
            }
            /*compute the valtage of the water*/
            int h=Math.min(A[slow],next[1]);
            for(int i=slow+1;i<next[0];i++){
                v+=(h-A[i]);
            }
            /*find the next slow pointer*/
            slow=next[0];
        }
        return v;
    }
    public int[] findPointer(int height,int start,int[] A,int len){
        int[] val=new int[2]; // maintain the position of the more than or equal to herghi or the maximum height;
        int max=0;
        for(int i=start;i<len;i++){
            if(A[i]>=height){
                val[0]=i;
                val[1]=A[i];
                break;
            }else{
                if(A[i]>max){
                    val[0]=i;
                    val[1]=A[i];
                    max=A[i];
                }
            }
        }
        return val;
        
        
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值