java solution,easy to understand


  • 0
    X

    public int trap(int[] height) {

        int res=0;
    	int len=height.length;
    	if(len<=2)
    		return 0;
    	int s=0,e=len-1;
    	int lh=height[s],rh=height[e];
    	while(s<e){
    		if(lh>=rh){
    			int ch=height[e-1];
    			if(ch<rh){
    				res+=rh-ch;
    				e--;
    			}
    			else{
    				rh=ch;
    				e--;
    			}
    		}
    		else if(lh<rh){
    			int ch=height[s+1];
    			if(ch<lh){
    				res+=lh-ch;
    				s++;
    			}
    			else{
    				lh=ch;
    				s++;
    			}
    		}
    	}	
    	return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.