代码随想录训练营第五十九天|LeetCode 503、42

LeetCode 503下一个更大元素II

题目链接:503.下一个更大元素II

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int> ans(nums.size());
        //先找数组中值最大的元素下标
        int maxNum = nums[0];
        int index = 0;
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i] > maxNum) {
                maxNum = nums[i];
                index = i;
            }
        }
        //从最大元素位置开始遍历
        stack<int> st;
        int size = nums.size();
        for (int i = index + size; i >= index + 1; --i) {
            while (!st.empty() && st.top() <= nums[i % size]) {
                st.pop();
            }
            if (st.empty()) ans[i % size] = -1;
            else ans[i % size] = st.top();
            st.push(nums[i % size]);
        }
        return ans;
    }
};

LeetCode 42接雨水

题目链接:42.接雨水

//动态规划
class Solution {
public:
    int trap(vector<int>& height) {
        int ans = 0;
        vector<int> maxLeft(height.size(), 0);
        vector<int> maxRight(height.size(), 0);

        maxLeft[0] = height[0];
        for (int i = 1; i < height.size(); ++i) {
            maxLeft[i] = max(height[i], maxLeft[i - 1]);
        }

        maxRight[height.size() - 1] = height[height.size() - 1];
        for (int j = height.size() - 2; j >= 0; --j) {
            maxRight[j] = max(height[j], maxRight[j + 1]);
        }

        for (int k = 0; k < height.size(); ++k) {
            ans += min(maxLeft[k], maxRight[k]) - height[k];
        }
        return ans;
    }
};
//空间优化版双指针
class Solution {
public:
    int trap(vector<int>& height) {
        int result = 0;
        int left = 0, right = height.size() - 1;
        int leftMax = 0, rightMax = 0;
        while (left < right) {
            leftMax = max(height[left], leftMax);
            rightMax = max(height[right], rightMax);
            if (height[left] < height[right]) {//必有leftMax<rightMax
                result += leftMax - height[left];
                ++left;
            }
            else {
                result += rightMax - height[right];
                --right;
            }
        }
        return result;
    }
};
//单调栈——按照行来处理
class Solution {
public:
    int trap(vector<int>& height) {
        int result = 0;
        stack<int> st;
        for (int i = 0; i < height.size(); ++i) {
            while (!st.empty() && height[st.top()] <= height[i]) {
                int temp = height[st.top()]; st.pop();
                if (!st.empty()) result += (min(height[i], height[st.top()]) - temp) * (i - st.top() - 1);
            }
            st.push(i); 
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值