Java Short and Easy to understand two pointers solution


  • 2
    A
    public int trap(int[] height) {
        if(height == null || height.length == 0){
            return 0;
        }
        int rain = 0;
        int low = 0;
        int high = height.length - 1;
        int curMin = 0;
        while(low < high){
            if(height[low] <= curMin){
                rain += curMin - height[low];
                ++low;
            }else if(height[high] <= curMin){
                rain += curMin - height[high];
                --high;
            }else{
                curMin = Math.min(height[low], height[high]);
            }
        }
        return rain;
    }

Log in to reply
 

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