739. 每日温度
今天正式开始单调栈,这是单调栈一篇扫盲题目,也是经典题。
大家可以读题,思考暴力的解法,然后在看单调栈的解法。 就能感受出单调栈的巧妙
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int length = temperatures.length;
int[] result = new int[length];
Deque<Integer> stack = new LinkedList<>();
for (int i = 0; i < length; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
result[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
return result;
}
}
496.下一个更大元素 I
本题和 739. 每日温度 看似差不多,其实 有加了点难度。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> stack = new Stack<>();
int[] result = new int[nums1.length];
Arrays.fill(result, -1);
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums1.length; i++) {
map.put(nums1[i], i);
}
stack.push(0);
for (int i = 1; i < nums2.length; i++) {
if (nums2[i] <= nums2[stack.peek()]) {
stack.push(i);
} else {
while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
if (map.containsKey(nums2[stack.peek()])) {
Integer index = map.get(nums2[stack.peek()]);
result[index] = nums2[i];
}
stack.pop();
}
stack.push(i);
}
}
return result;
}
}
503.下一个更大元素II
这道题和 739. 每日温度 几乎如出一辙,可以自己尝试做一做
class Solution {
public int[] nextGreaterElements(int[] nums) {
if (nums == null || nums.length <= 1) {
return new int[]{-1};
}
int length = nums.length;
int[] results = new int[length];
Arrays.fill(results, -1);
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < 2 * length; i++) {
while (!stack.isEmpty() && nums[i % length] > nums[stack.peek()]) {
results[stack.peek()] = nums[i % length];
stack.pop();
}
stack.push(i % length);
}
return results;
}
}