单调栈模板
public int[] nextGreaterElement(int[] nums) {
// 输⼊ nums = [2,1,2,4,3],返回 [4,2,4,-1,-1]
Stack<Integer> s = new Stack<>();
int[] res = new int[nums.length];
for (int i = nums.length - 1;i >= 0;i--){
while (!s.isEmpty() && s.peek() <= nums[i]){
s.pop();
}
res[i] = s.isEmpty() ? -1 : s.peek();
s.push(nums[i]);
}
return res;
}
739. 每日温度
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,
其中 answer[i] 是指在第 i 天之后,才会有更高的温度。
如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90]
输出: [1,1,0]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
// lc 239
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> s = new Stack<>();
// 栈中存放 索引
int[] res = new int[temperatures.length];
for (int i = temperatures.length - 1;i >= 0;i--){
while (!s.isEmpty() && temperatures[s.peek()] <= temperatures[i]){
s.pop();
}
res[i] = s.isEmpty() ? 0 : s.peek()-i;
s.push(i);
}
return res;
}
}
503. 下一个更大元素 II
给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),
返回 nums 中每个元素的 下一个更大元素 。
数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,
这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。
示例 1:
输入: nums = [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
示例 2:
输入: nums = [1,2,3,4,3]
输出: [2,3,4,-1,4]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> s = new Stack<>();
int len = nums.length;
int[] res = new int[len];
for (int i = len - 1;i >= 0;i--){
while (!s.isEmpty() && s.peek() <= nums[i]){
s.pop();
}
if (s.isEmpty()){
for (int j = (i+1)%len;j != i;j = (j+1)%len ){
if (nums[j] > nums[i]){
s.push(nums[j]);
break;
}
}
}
res[i] = s.isEmpty() ? -1 : s.peek();
s.push(nums[i]);
}
return res;
}
}
方法二(推荐)
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> s = new Stack<>();
int len = nums.length;
int[] res = new int[len];
// nums = [1,2,3,4,3]
// 假设数组现在是 [1,2,3,4,3][1,2,3,4,3]
for (int i = 2 * len - 1;i >= 0;i--){
while (!s.isEmpty() && s.peek() <= nums[i % len]){
s.pop();
}
res[i % len] = s.isEmpty() ? -1 : s.peek();
s.push(nums[i % len]);
}
return res;
}
}
方法二分析:
将数组长度翻倍