739. 每日温度(入门)

Untitled

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Deque<Integer> queue = new LinkedList<Integer>();
        int n = temperatures.length;
        int[] ans = new int[n];
        
        for(int i = 0; i < n; i++) {
            while(!queue.isEmpty() && temperatures[queue.peekFirst()] < temperatures[i]) {
                int idx = queue.removeFirst();
                ans[idx] = i - idx;
            }
            queue.addFirst(i);
        }
        while(!queue.isEmpty()) {
            int idx = queue.removeFirst();
            ans[idx] = 0;
        }
        return ans;
    }
}

901. 股票价格跨度(单调栈+Map)

class StockSpanner {
    Deque<Integer> stack;
    Map<Integer,Integer> map;

    StockSpanner() {
        stack = new LinkedList<>();
        map = new HashMap<>();
    }
    
    int next(int price) {
        int ans = 1;
        // 如果比当前值小,加上一个元素的答案
        while(!stack.isEmpty() && stack.getFirst() <= price ) { // 
            int idx = stack.removeFirst();
            ans += map.get(idx);
            map.remove(idx);
        }
        stack.addFirst(price);
        map.put(price, ans);
        return ans;
    }
};