Day59 单调栈 LC 503 42

91 阅读1分钟

503. 下一个更大元素 II

心得

  • 直接拼接,插入复杂度O(n),需要优化,可以通过索引技巧来优化

题解

  • 循环数组处理办法可以通过2*size 然后i % sum.size()来遍历
class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int> result(nums.size(), -1);
        stack<int> st;
        for (int i = 0; i < nums.size() * 2; i++) {
            while (!st.empty() && nums[i % nums.size()] > nums[st.top()]) {
                result[st.top()] = nums[i % nums.size()];
                st.pop();
            }
            st.push(i % nums.size());
        }
        return result;
    }
};

42. 接雨水

心得

题解

  • 单调栈法:本质是按行来求取,通过单调栈来找到右边第一个比其大的元素,然后由于单调栈,前一个位置即为左边第一个大于该处的值,木桶求最短与对应宽度即可
  • 双指针法:求列可以装的最大,需要找到左右侧最高取其min,然后该列宽度1即可求得,暴力即为O(N^2)在此基础上优化到O(n)
  • 注意一个找左右第一个大,按行求解,另一个找左右最大,按列求解
// 单调栈O(n) O(n)
class Solution {
public:
    int trap(vector<int>& height) {
        if (height.size() <= 2) return 0;
        int sum = 0;
        stack<int> st;
        st.push(0);
        for (int i = 1; i < height.size(); i++) {
            if (height[i] < height[st.top()]) {
                st.push(i);
            } else if (height[i] == height[st.top()]) {
                st.pop(); // 可不加,仅多一次计算
                st.push(i);
            } else {
                while (!st.empty() && height[i] > height[st.top()]) {
                    int mid = st.top();
                    st.pop();
                    if (!st.empty()) {
                        int h = min(height[i], height[st.top()]) - height[mid];
                        int w = i - st.top() - 1;
                        sum += w * h;
                    }
                }
                st.push(i);
            }
        }
        return sum;
    }
};
// 双指针
class Solution {
public:
    int trap(vector<int>& height) {
        if (height.size() <= 2) return 0;
        vector<int> maxLeft(height.size(), 0);
        vector<int> maxRight(height.size(), 0);
        int size = maxRight.size();

        // 记录每个柱子左边柱子最大高度
        maxLeft[0] = height[0];
        for (int i = 1; i < size; i++) {
            maxLeft[i] = max(height[i], maxLeft[i - 1]);
        }
        // 记录每个柱子右边柱子最大高度
        maxRight[size - 1] = height[size - 1];
        for (int i = size - 2; i >= 0; i--) {
            maxRight[i] = max(height[i], maxRight[i + 1]);
        }
        // 求和
        int sum = 0;
        for (int i = 0; i < size; i++) {
            int count = min(maxLeft[i], maxRight[i]) - height[i];
            if (count > 0) sum += count;
        }
        return sum;
    }
};