代码随想录算法训练营day58 | 739. 每日温度,496.下一个更大元素 I
739. 每日温度
教程视频:https://www.bilibili.com/video/BV1my4y1Z7jj
解法一:单调栈(视频版)
遍历时将已经遍历的元素,存入栈中,期间保持栈顶到栈底为递增的。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] answer = new int[temperatures.length];
Deque<Integer> stack=new LinkedList<>();
stack.push(0);
for(int i=1;i<temperatures.length;i++){
if(temperatures[i]<=temperatures[stack.peek()]){
stack.push(i);
}else{
while(!stack.isEmpty() && temperatures[i]>temperatures[stack.peek()]){
answer[stack.peek()]=i-stack.peek();
stack.pop();
}
stack.push(i);
}
}
return answer;
}
}
解法二:单调栈(自己写的,反向遍历)
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] answer = new int[temperatures.length];
// Stack<Integer> stack = new Stack<>();
Deque<Integer> stack=new LinkedList<>();
for(int i=temperatures.length-1;i>=0;i--){
while(!stack.isEmpty() && temperatures[i]>=temperatures[stack.peek()]){
stack.pop();
}
if(stack.isEmpty()){
answer[i]=0;
}else{
answer[i] = stack.peek()-i;
}
stack.push(i);
}
return answer;
}
}
496.下一个更大元素 I
教程视频:https://www.bilibili.com/video/BV1jA411m7dX
解法一:单调栈(自己写的,复杂)
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Deque<Integer> stack = new LinkedList<>();
int[] result = new int[nums2.length];
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[i]>nums2[stack.peek()]){
result[stack.peek()]=i-stack.peek();
stack.pop();
}
stack.push(i);
}
}
// while(!stack.isEmpty()){
// result[stack.pop()]=-1;
// }
for(int j=0;j<nums2.length;j++){
System.out.println(result[j]);
}
int[] result2 = new int[nums1.length];
for(int i=0;i<nums1.length;i++){
for(int j=0;j<nums2.length;j++){
if(nums1[i]==nums2[j]){
if(result[j]==0){
result2[i]=-1;
}else{
result2[i]=nums2[j+result[j]];
}
}
}
}
return result2;
}
}
解法二:单调栈(视频教程版)
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> temp = new Stack<>();
int[] res = new int[nums1.length];
Arrays.fill(res,-1);
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0 ; i< nums1.length ; i++){
hashMap.put(nums1[i],i);
}
temp.add(0);
for (int i = 1; i < nums2.length; i++) {
if (nums2[i] <= nums2[temp.peek()]) {
temp.add(i);
} else {
while (!temp.isEmpty() && nums2[temp.peek()] < nums2[i]) {
if (hashMap.containsKey(nums2[temp.peek()])){
Integer index = hashMap.get(nums2[temp.peek()]);
res[index] = nums2[i];
}
temp.pop();
}
temp.add(i);
}
}
return res;
}
}
总结
1、单调栈存放的是数组下标,这样可以更方便的查询元素并获取距离。