Share my initial java code


  • 0
    M

    public int trap(int[] height) {
    // two loop
    // left max and right max
    // http://blog.csdn.net/linhuanmars/article/details/20888505
    if(height == null || height.length == 0) return 0;
    int len = height.length;
    int[] left = new int[len];
    int[] right = new int[len];
    int max = height[0];
    left[0] = max;
    for(int i = 1; i < len; i++) {
    left[i] = Math.max(max, height[i]);
    max = Math.max(max, height[i]);
    }

        // second loop from right to left
        max = height[len - 1];
        right[len - 1] = max;
        for(int i = len - 1; i >- 0; i--) {
            right[i] = Math.max(max, height[i]);
            max = Math.max(max, height[i]);
        }
        
        // last loop to calu evry bar container c[i] = Min(left[i], right[i]) - height[i] * 1
        int count = 0;
        for(int i = 0; i < len; i++) {
            int temp = Math.min(left[i], right[i]) - height[i];
            if(temp > 0) count += temp;
        }
        return count;
    }

Log in to reply
 

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