Leetcode 503.下一个更大元素II
题目链接
思路:单调栈
代码:
class Solution {
public int[] nextGreaterElements(int[] nums) {
if(nums == null || nums.length <= 1) {
return new int[]{-1};
}
int size = nums.length;
int[] result = new int[size];
Arrays.fill(result,-1);
// 栈中存放的是nums中的元素下标
Stack<Integer> st= new Stack<>();
for(int i = 0; i < size * 2; i++) {
while(!st.empty() && nums[i % size] > nums[st.peek()]) {
// 更新result
result[st.peek()] = nums[i % size];
// 弹出栈顶
st.pop();
}
st.push(i % size);
}
return result;
}
}
Leetcode 42. 接雨水
方法一:双指针法
思路:双指针法
代码:
class Solution {
public int trap(int[] height) {
// 双指针法
int sum = 0;
for (int i = 0; i < height.length; i++) {
// 第一个柱子和最后一个柱子不接水
if (i == 0 || i == height.length - 1) {
continue;
}
// 记录左边柱子的最高高度
int lHeight = height[i];
// 记录右边柱子的最高高度
int rHeight = height[i];
for (int l = i - 1; l >= 0; l--) {
if (height[l] > lHeight) {
lHeight = height[l];
}
}
for (int r = i + 1; r < height.length; r++) {
if (height[r] > rHeight) {
rHeight = height[r];
}
}
int h = Math.min(lHeight, rHeight) - height[i];
if (h > 0) {
sum += h;
}
}
return sum;
}
}
方法二:动态规划
思路:动态规划
代码:
class Solution {
public int trap(int[] height) {
// 动态规划
int length = height.length;
if (length <= 2) {
return 0;
}
int[] maxLeft = new int[length];
int[] maxRight = new int[length];
// 记录每个柱子左边柱子最大高度
maxLeft[0] = height[0];
for (int i = 1; i < length; i++) {
maxLeft[i] = Math.max(height[i], maxLeft[i - 1]);
}
// 记录每个柱子右边柱子最大高度
maxRight[length - 1] = height[length - 1];
for (int i = length - 2; i >= 0; i--) {
maxRight[i] = Math.max(height[i], maxRight[i + 1]);
}
// 求和
int sum = 0;
for (int i = 0; i < length; i++) {
int count = Math.min(maxLeft[i], maxRight[i]) - height[i];
if (count > 0) {
sum += count;
}
}
return sum;
}
}