Java solution with two pointers


  • 0
    Y
    public int trap(int[] height) {
        int res = 0;
        if (height == null)
            return res;
            
        int n = height.length;
        int left = 0;
        int right = n - 1;
        
        while (left + 1 < right) {
            if (height[left] < height[right]) {
                if (height[left + 1] < height[left]) {
                    res += height[left] - height[left + 1];
                    height[left + 1] = height[left];
                }
                left++;
            } else {
                if (height[right - 1] < height[right]) {
                    res += height[right] - height[right - 1];
                    height[right - 1] = height[right];
                }
                right--;                
            }
        }
        
        return res;
    }

Log in to reply
 

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