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;
}
};