LeetCode 503下一个更大元素II
题目简析:
给定一个循环数组 nums
( nums[nums.length - 1]
的下一个元素是 nums[0]
),返回 nums
中每个元素的 下一个更大元素 ,循环数组中去找。
思路分析:
本题难点在于如何模拟循环数组来检索
我们只需要处理遍历的长度为2*len,然后用当前下标去%len,其余的内容就跟每日温度一样啦
//本题难点就是如何模拟循环数组
public int[] nextGreaterElements(int[] nums) {
int len = nums.length;
//因为找不到就是-1,那么我们就得先将数组初始化为-1
int []res = new int[len];
Arrays.fill(res,-1);
if (len == 0) return res;
//单调栈的做法就是存下标然后通过下标去原来数组找值
//通过两者比对来确定结果
Stack<Integer> stack = new Stack<>();
//注意数组中结果的是值
for (int i = 0; i < len*2; i++) {
// 模拟遍历两边nums,注意一下都是用i % len来操作
while (!stack.isEmpty() && nums[i % len] > nums[stack.peek()]) {
res[stack.peek()] = nums[i % len];
stack.pop();
}
stack.push(i % len);
}
return res;
}
LeetCode 42接雨水
题目简析:
给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
思路分析:
本题一刷就了解的不太到位了,后面复习再来
public int trap(int[] height){
int size = height.length;
if (size <= 2) return 0;
// in the stack, we push the index of array
// using height[] to access the real height
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
int sum = 0;
for (int index = 1; index < size; index++){
int stackTop = stack.peek();
if (height[index] < height[stackTop]){
stack.push(index);
}else if (height[index] == height[stackTop]){
// 因为相等的相邻墙,左边一个是不可能存放雨水的,所以pop左边的index, push当前的index
stack.pop();
stack.push(index);
}else{
//pop up all lower value
int heightAtIdx = height[index];
while (!stack.isEmpty() && (heightAtIdx > height[stackTop])){
int mid = stack.pop();
if (!stack.isEmpty()){
int left = stack.peek();
int h = Math.min(height[left], height[index]) - height[mid];
int w = index - left - 1;
int hold = h * w;
if (hold > 0) sum += hold;
stackTop = stack.peek();
}
}
stack.push(index);
}
}
return sum;
}