Merge pull request #381 from minghaha/master

0739 单调栈
This commit is contained in:
程序员Carl
2021-06-11 15:38:14 +08:00
committed by GitHub

View File

@ -180,7 +180,36 @@ public:
Java
```java
/**
* 单调栈,栈内顺序要么从大到小 要么从小到大,本题从大到笑
* <p>
* 入站元素要和当前栈内栈首元素进行比较
* 若大于栈首则 则与元素下标做差
* 若大于等于则放入
*
* @param temperatures
* @return
*/
public static int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
/**
* 取出下标进行元素值的比较
*/
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int preIndex = stack.pop();
res[preIndex] = i - preIndex;
}
/**
* 注意 放入的是元素位置
*/
stack.push(i);
}
return res;
}
```
Python
Go