42. Trapping Rain Water

JJ·2021년 2월 2일
0

Algorithms

목록 보기
92/114
class Solution {
    public int trap(int[] height) {
        int rain = 0; 
        if (height.length > 0) {
            int before = height[0];
            for (int i = 1; i < height.length - 1; i++) {
                if (height[i] == 0) {
                    rain += 0;
                } else {
                    if (before > height[i]) {
                        rain += height[i];
                    } else {
                        rain += before;
                    }
                    before = height[i];
                }       
            }
        }
        return rain;
    }
}

작년에 baby좌가 풀어놨던것~~~
WRONG ANSWER ^^

과연 new 좌는 얼마나 성장했을지?

class Solution {
    public int trap(int[] height) {
        int rain = 0;
        
        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] >= leftMax) {
                    leftMax = height[left];
                } else {
                    rain += leftMax - height[left];
                }
                left++;
            } else {
                if (height[right] >= rightMax) {
                    rightMax = height[right];
                } else {
                    rain += rightMax - height[right];
                }
                right--;
            }
        }
        
        return rain;
    }
}

Runtime: 1 ms, faster than 85.26% of Java online submissions for Trapping Rain Water.
Memory Usage: 40.7 MB, less than 5.87% of Java online submissions for Trapping Rain Water.

왼쪽과 오른쪽을 떙기면서 서로를 비교하는 방식~

Runtime: 1 ms, faster than 85.26% of Java online submissions for Trapping Rain Water.
Memory Usage: 40.7 MB, less than 5.87% of Java online submissions for Trapping Rain Water.

0개의 댓글