LeetCode739. 每日温度
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];
Deque<int[]> deque = new ArrayDeque<>();
deque.push(new int[] {temperatures[0],0});
for(int index=1;index<temperatures.length;index++) {
if(temperatures[index]>deque.peek()[0]) {
while(!deque.isEmpty()&&temperatures[index]>deque.peek()[0]) {
int[] temp = deque.pop();
res[temp[1]]=index-temp[1];
}
}
deque.push(new int[] {temperatures[index], index});
}
return res;
}
LeetCode496.下一个更大元素 I
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
Arrays.fill(res, -1);
Map<Integer,Integer> hash = new HashMap<>();
for(int i=0;i<nums1.length;i++) {
hash.put(nums1[i], i);
}
Deque<int[]> deque = new ArrayDeque<>();
deque.push(new int[] {nums2[0],hash.getOrDefault(nums2[0], -1)});
for(int index=1;index<nums2.length;index++) {
if(nums2[index]>deque.peek()[0]) {
while(!deque.isEmpty()&&nums2[index]>deque.peek()[0]) {
int[] temp = deque.pop();
if(temp[1]!=-1) {
res[temp[1]]=nums2[index];
}
}
}
deque.push(new int[] {nums2[index], hash.getOrDefault(nums2[index], -1)});
}
return res;
}
LeetCode503.下一个更大元素II
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Arrays.fill(res, -1);
Deque<int[]> deque = new ArrayDeque<>();
deque.push(new int[] {nums[0],0});
for(int index=1;index<nums.length;index++) {
if(nums[index]>deque.peek()[0]) {
while(!deque.isEmpty()&&nums[index]>deque.peek()[0]) {
int[] temp = deque.pop();
res[temp[1]]=nums[index];
}
}
deque.push(new int[] {nums[index], index});
}
for(int index=0;index<nums.length;index++) {
if(!deque.isEmpty()&&nums[index]>deque.peek()[0]) {
while(!deque.isEmpty()&&nums[index]>deque.peek()[0]) {
int[] temp = deque.pop();
if(res[temp[1]]==-1) {
res[temp[1]]=nums[index];
}
}
}
deque.push(new int[] {nums[index], index});
}
return res;
}