模板
class Solution {
public int[] f(int[] nums) {
Stack<Integer> stack=new Stack<>();
int n=nums.length;
int[] res=new int[n];
for(int i=n-1;i>=0;i--){
while(!stack.isEmpty()&&nums[i]>=nums[..]) stack.pop();
if(!stack.isEmpty()) res[i]=..;//题目给的条件
stack.push(i);
}
return res;
}
}
每日温度(LeetCode739)
模板题
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack=new Stack<>();
int n=temperatures.length;
int[] res=new int[n];
for(int i=n-1;i>=0;i--){
while(!stack.isEmpty()&&temperatures[i]>=temperatures[stack.peek()]) stack.pop();
if(!stack.isEmpty()) res[i]=stack.peek()-i;
stack.push(i);
}
return res;
}
}
下一个更大的元素I(LeetCode496)
模板题
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> stk = new Stack<>();
int[] q = new int[nums2.length];
for (int i = nums2.length - 1; i >= 0; i--) {
int x = nums2[i];
while (!stk.isEmpty() && x >= stk.peek()) stk.pop();
q[i] = stk.isEmpty() ? -1 : stk.peek();
stk.push(x);
}
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < nums2.length; i++)
hash.put(nums2[i], i);
int[] res = new int[nums1.length];
for(int i=0;i<nums1.length;i++){
res[i]=q[hash.get(nums1[i])];
}
return res;
}
}
下一个更大的元素II(LeetCode503)
这种环形,就是开一个二倍数组即可。
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n=nums.length;
int[] num=new int[2*n];
for(int i=0;i<2*n;i++){
num[i]=nums[i%n];
}
int[] res=new int[n];
Stack<Integer> stack=new Stack<>();
for(int i=2*n-1;i>=0;i--){
while(stack.size()!=0&&num[i]>=stack.peek()) stack.pop();
if(stack.size()!=0&&i<n) res[i]=stack.peek();
else if(stack.size()==0&&i<n) res[i]=-1;
stack.push(num[i]);
}
return res;
}
}