下一个更大元素
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
HashMap<Integer,Integer> map=new HashMap<>();
Stack<Integer> s=new Stack<>();
for(int i=nums2.length-1;i>=0;i--){
while(!s.isEmpty()&&s.peek()<=nums2[i]){
s.pop();
}
map.put(nums2[i],s.isEmpty()?-1:s.peek());
s.push(nums2[i]);
}
int[] ans=new int[nums1.length];
for(int i=0;i<nums1.length;i++){
ans[i]=map.get(nums1[i]);
}
return ans;
}
}
下一个更大元素(环形数组)
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> s = new Stack<>();
int n=nums.length;
int[] res=new int[n];
for(int i=2*n-1;i>=0;i--){
while(!s.isEmpty()&&s.peek()<=nums[i%n]){
s.pop();
}
res[i%n] = s.isEmpty()?-1:s.peek();
s.push(nums[i%n]);
}
return res;
}
}
每日温度
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int len = temperatures.length;
Stack<Integer> s=new Stack<>();
int[] ans=new int[len];
for(int i=temperatures.length-1;i>=0;i--){
while(!s.isEmpty()&&temperatures[s.peek()]<=temperatures[i]){
s.pop();
}
ans[i]=s.isEmpty()?0:s.peek()-i;
s.push(i);
}
return ans;
}
}