leetcode-trapping rain water

来源:互联网 发布:mac os x 10.10 ios 编辑:程序博客网 时间:2024/06/06 04:08

这是第一种方法:
/*maintain two pointers, think of it has real live water..fill the container from two sideshow 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 0