Skip to content

Commit 451a781

Browse files
committed
901.股票价格跨度,单调递减栈
1 parent 61e87f4 commit 451a781

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@
101101
714. 买卖股票的最佳时机含手续费
102102
718. 最长重复子数组
103103
739. 每日温度
104+
901. 股票价格跨度
104105
1020. 飞地的数量
105106
1035. 不相交的线
106107
1081. 不同字符的最小子序列

leetcode_Java/Solution0901.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// 901. 股票价格跨度
2+
3+
4+
/**
5+
* Your StockSpanner object will be instantiated and called as such:
6+
* StockSpanner obj = new StockSpanner();
7+
* int param_1 = obj.next(price);
8+
*/
9+
10+
11+
/*
12+
单调递减栈:
13+
1、栈存放索引,表示日期,方便计算最大连续日数
14+
2、栈不为空 且 当前价格大于栈顶价格,则弹出栈顶价格
15+
3、栈为空说明入栈的价格都弹出来了,跨度就是列表的长度
16+
4、栈不为空,则计算栈顶日期与今天的日期差,得到跨度
17+
*/
18+
class StockSpanner {
19+
Deque<Integer> stack;
20+
List<Integer> list;
21+
22+
public StockSpanner() {
23+
stack = new ArrayDeque<>();
24+
list = new ArrayList<>();
25+
}
26+
27+
public int next(int price) {
28+
int res = 0;
29+
list.add(price);
30+
while (!stack.isEmpty() && price >= list.get(stack.peek())) {
31+
stack.pop();
32+
}
33+
if (stack.isEmpty()) {
34+
res = list.size();
35+
} else {
36+
res = list.size() - 1 - stack.peek();
37+
}
38+
stack.push(list.size() - 1);
39+
return res;
40+
}
41+
}
42+

0 commit comments

Comments
 (0)