mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
修改739 每日温度的 Java 代码,并增加注释
This commit is contained in:
@ -177,34 +177,60 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
```java
|
||||||
/**
|
|
||||||
* 单调栈,栈内顺序要么从大到小 要么从小到大,本题从大到小
|
class Solution {
|
||||||
* <p>
|
// 版本 1
|
||||||
* 入站元素要和当前栈内栈首元素进行比较
|
public int[] dailyTemperatures(int[] temperatures) {
|
||||||
* 若大于栈首则 则与元素下标做差
|
|
||||||
* 若大于等于则放入
|
int lens=temperatures.length;
|
||||||
*
|
int []res=new int[lens];
|
||||||
* @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++) {
|
注意,单调栈里 加入的元素是 下标。
|
||||||
/**
|
*/
|
||||||
* 取出下标进行元素值的比较
|
Stack<Integer>stack=new Stack<>();
|
||||||
*/
|
stack.push(0);
|
||||||
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
|
for(int i=1;i<lens;i++){
|
||||||
int preIndex = stack.pop();
|
|
||||||
res[preIndex] = i - preIndex;
|
if(temperatures[i]<=temperatures[stack.peek()]){
|
||||||
|
stack.push(i);
|
||||||
|
}else{
|
||||||
|
while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
|
||||||
|
res[stack.peek()]=i-stack.peek();
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
stack.push(i);
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* 注意 放入的是元素位置
|
|
||||||
*/
|
|
||||||
stack.push(i);
|
|
||||||
}
|
}
|
||||||
return res;
|
|
||||||
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//--------这 是一条分界线
|
||||||
|
// 版本 2
|
||||||
|
class Solution {
|
||||||
|
public int[] dailyTemperatures(int[] temperatures) {
|
||||||
|
int lens=temperatures.length;
|
||||||
|
int []res=new int[lens];
|
||||||
|
Stack<Integer>stack=new Stack<>();
|
||||||
|
for(int i=0;i<lens;i++){
|
||||||
|
|
||||||
|
while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
|
||||||
|
res[stack.peek()]=i-stack.peek();
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
stack.push(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
```
|
```
|
||||||
Python:
|
Python:
|
||||||
``` Python3
|
``` Python3
|
||||||
|
Reference in New Issue
Block a user