leetcode 739
题目链接
输出要想观测到 warmer temperature,至少需要等待的天数
思路:
- 单调栈 (monotonic stack) 经典题目,可使用单调栈的情况:一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置
- 用栈来记录遍历过的元素,可以只存放下标
- 考虑3种情况:
栈顶 < A[i]
:栈顶弹出,i
入栈,res[stack.top()] = i - stack.top()
栈顶 > A[i]
:i
入栈栈顶 == A[i]
:i
入栈
- 题解
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];
Stack<Integer> stack = new Stack<>();
stack.push(0);
for (int i = 1; i < temperatures.length; ++i) {
if (temperatures[stack.peek()] >= temperatures[i])
stack.push(i);
else {
while (!stack.empty() && temperatures[stack.peek()] < temperatures[i]) {
res[stack.peek()] = i - stack.peek();
stack.pop(); //弹出
}
stack.push(i);
}
}
return res;
}
}
leetcode 496
思路:
- 基本 like leetcode 739
- 需要用到
HashMap
- 代码随想录题解,代码所用变量更少,占空间更少
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
int[] temp = new int[nums2.length];
Map<Integer, Integer> map = new HashMap<>();
Deque<Integer> stack = new LinkedList<>();
stack.push(0);
map.put(nums2[0], 0);
for (int i = 1; i < nums2.length; ++i) {
map.put(nums2[i], i);
if (nums2[stack.peek()] >= nums2[i])
stack.push(i);
else {
while(!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
temp[stack.peek()] = i;
stack.pop();
}
stack.push(i);
}
}
int i = 0;
for (int x : nums1) {
if (temp[map.get(x)] == 0)
res[i++] = -1;
else
res[i++] = nums2[temp[map.get(x)]];
}
return res;
}
}