代码随想录-2023/08/26

63 阅读1分钟

单调栈

739.每日温度

解题思路:

  1. 双重for循环寻找超时
  2. 维护一个单调递减栈, 存储下标, 当找到比当前位置大的元素就记录

代码:

class Solution {
    // 暴力法超时
    public int[] dailyTemperatures(int[] t) {
        int n = t.length;
        int[] a= new int[n];
        // 维护一个单调递减栈
        Deque<Integer> deque = new ArrayDeque<>();
        for(int i=0; i<n; i++){
            if(deque.isEmpty()) deque.push(i);
            else{
                while(!deque.isEmpty() && t[i] > t[deque.peek()]){
                    a[deque.peek()] = i - deque.pop();
                }
                deque.push(i);
            }
        }

        return a;
    }
}

496.下一个更大元素I

解题思路:

  1. 类似于上一题: 对nums2进行每日温度查询,并存入哈希表
  2. 遍历nums1, 在哈希表中找到下一个更大元素, 若找不到则置为-1

代码:

class Solution {
    // 跟每日温度一样
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] arr = new int[nums1.length];
        HashMap<Integer, Integer> map = new HashMap<>();
        // 维护一个单调递减栈
        Deque<Integer> deque = new ArrayDeque<>();
        for(int i=0; i<nums2.length; i++){
            if(deque.isEmpty()) deque.push(i);
            else{
                while(!deque.isEmpty() && nums2[i] > nums2[deque.peek()]){
                    map.put(nums2[deque.pop()], nums2[i]);
                }
                deque.push(i);
            }
        }
        for(int i=0; i<nums1.length; i++){
            arr[i] = map.getOrDefault(nums1[i], -1);
        }

        return arr;
    }
}