Is it the best answer?


  • 1
    A
    public class Solution {
    public int trap(int[] A) {
    	int len = A.length;
    	if(len < 3)return 0;
    	int sum = 0;
    	int left = 0;
    	int lheight = A[left];
    	int right = len - 1;
    	int rheight = A[right];
    	while(left < right){
    		while(left < right && lheight <= rheight){
    			left++;
    			if(A[left] < lheight){
    				sum += lheight - A[left];
    			}else
    				lheight = A[left];
    		}
    		while(left < right && lheight > rheight){
    			right--;
    			if(A[right] < rheight){
    				sum += rheight - A[right];
    			}else
    				rheight = A[right];
    		}
    	}
    	return sum;        
    }
    

    }


  • 0
    Y

    The parameter A can be null,it causes NullPointerException.


Log in to reply
 

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