LeetCode 901 title: stock price span (monotonous stack)

Address: https: //leetcode-cn.com/problems/online-stock-span/

Knowledge points:

  • Continuous or less left to find their own element, monotonous stack is specifically to solve this problem, so in addition to violence law is this method;
  • Stack problem generally monotonous record index;
  • Here the data is dynamic, it is convenient is that you can use sentinel, so do not consider the special situation.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class StockSpanner {

    private List<Integer> stock;

    /**
     * Java 官方推荐使用 Deque,只用和栈相关的接口
     */
    private Deque<Integer> indexes;

    private int index;

    public StockSpanner() {

        // 哨兵,这个元素永远不会出栈
        stock = new ArrayList<>();
        stock.add(10_0000 + 1);

        indexes = new ArrayDeque<>();
        indexes.addLast(0);
        index = 0;
    }

    public int next(int price) {
        index++;

        // 特别注意:不要用 indexes.peek(),这个方法等价于 peekFirst()
        while (!indexes.isEmpty() && stock.get(indexes.peekLast()) <= price) {
            indexes.removeLast();
        }

        // 因为 indexes 后面会更改,因此这里先把结果暂存一下
        int res =  index - indexes.peekLast() ;

        stock.add(price);
        indexes.addLast(index);

        return res;
    }
}
Published 434 original articles · won praise 325 · Views 1.23 million +

Guess you like

Origin blog.csdn.net/lw_power/article/details/103957702