程式碼隨想錄演算法訓練營 | 42. 接雨水,84. 柱狀圖中最大的矩形

漪欢酒發表於2024-10-22

42. 接雨水
題目連結:42. 接雨水
文件講解︰程式碼隨想錄(programmercarl.com)
影片講解︰接雨水
日期:2024-10-21

Java程式碼如下:

class Solution {
    public int trap(int[] height){
        int size = height.length;
        if (size <= 2) return 0;

        Deque<Integer> st = new LinkedList<>();
        st.push(0);

        int sum = 0;
        for (int i = 1; i < size; i++){
            if (height[i] < height[st.peek()]){
                st.push(i);
            }else if (height[i] == height[st.peek()]){
                st.pop();
                st.push(i);
            }else{
                while (!st.isEmpty() && (height[i] > height[st.peek()])){
                    int mid = st.pop();
                    if (!st.isEmpty()){
                        int left = st.peek();

                        int h = Math.min(height[left], height[i]) - height[mid];
                        int w = i - left - 1;
                        int hold = h * w;
                        if (hold > 0) sum += hold;
                    }
                }
                st.push(i);
            }
        }

        return sum;
    }
}

84. 柱狀圖中最大的矩形
題目連結:84. 柱狀圖中最大的矩形
文件講解︰程式碼隨想錄(programmercarl.com)
影片講解︰柱狀圖中最大的矩形
日期:2024-10-21

Java程式碼如下:

class Solution {
    int largestRectangleArea(int[] heights) {
        Stack<Integer> st = new Stack<Integer>();
        
        int [] newHeights = new int[heights.length + 2];
        newHeights[0] = 0;
        newHeights[newHeights.length - 1] = 0;
        for (int index = 0; index < heights.length; index++){
            newHeights[index + 1] = heights[index];
        }

        heights = newHeights;
        
        st.push(0);
        int res = 0;
        for (int i = 1; i < heights.length; i++) {
            if (heights[i] > heights[st.peek()]) {
                st.push(i);
            } else if (heights[i] == heights[st.peek()]) {
                st.pop();
                st.push(i);
            } else {
                while (heights[i] < heights[st.peek()]) {
                    int mid = st.peek();
                    st.pop();
                    int left = st.peek();
                    int right = i;
                    int w = right - left - 1;
                    int h = heights[mid];
                    res = Math.max(res, w * h);
                }
                st.push(i);
            }
        }
        return res;
    }
}

相關文章