Skip to content

Update 算法--九阳神功.md #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 51 additions & 18 deletions 算法--九阳神功.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,24 +255,57 @@ List<Integer> diffWaysToCompute("(1 + 2 * 3) - (4 * 5)") {

```java
// 给你一个数组 temperatures,这个数组存放的是近几天的天气气温,你返回一个等长的数组,计算:对于每一天,你还要至少等多少天才能等到一个更暖和的气温;如果等不到那一天,填 0。
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];
Stack<Integer> descendStack = new Stack<>();
// 单调递减栈
for (int i = 0; i < temperatures.length; i++) {
// 栈非空时往里面加入比当前栈顶索引指向的元素大的元素--破坏了栈的单调性时
while (!descendStack.isEmpty() && temperatures[i] >= temperatures[descendStack.peek()]) {
// todo
// 移除栈顶元素
descendStack.pop();
}
// 得到索引间距
res[i] = descendStack.isEmpty() ? 0 : (descendStack.peek() - i);
// while结束,把更大的元素索引入栈
descendStack.push(i);
}
return res;
}
import java.util.Arrays;
import java.util.Stack;

/**
* 可信认证,九阳神功第一式:单调栈或单调队列
*
* 单调栈解决:元素左边第一个比当前观察元素小(单调递增栈) 元素左边第一个比当前观察元素大(单调递减栈),
*
* 即解决:--找出不按套路出牌的那个元素,
*
* (1)栈内(队列内)的存在单调顺序--这是正常时候
* (2)元素入栈之前会将破坏单调性的元素进行处理(因此,入栈前一般有一个while类循环)
*
* 本题: 给你一个数组 temperatures,这个数组存放的是近几天的天气气温,你返回一个等长的数组,
* 计算:对于每一天,你还要至少等多少天才能等到一个更暖和的气温;如果等不到那一天,填 0
*/

public class LeftDayForNextHotDay {
public static void main(String[] args) {
int[] temperatures1 = new int[]{73, 74, 75, 71, 69, 72, 76, 73};

int[] res1 = dailyTemperatures(temperatures1);
System.out.println(Arrays.toString(res1));
}

public static int[] dailyTemperatures(int[] tempratures) {
int[] res = new int[tempratures.length];

// 单调递减栈: 本来如果一天比一天温度低或不变,则不需要处理,只有当出现某一天温度上升了,破坏了一直不用处理的一天比一天不
Stack<Integer> descendStack = new Stack<>();

for (int i = 0; i < tempratures.length; i++) {
// 当前元素
int curTemp = tempratures[i];

// 栈非空时往里面加入比当前栈顶索引指向的元素大的元素--破坏了栈的单调性时
while (!descendStack.isEmpty() && curTemp >= tempratures[descendStack.peek()]) {
//
// 得到索引间距
res[descendStack.peek()] = i - descendStack.peek();

// 出栈不满足递减的在栈中的元素
descendStack.pop();
}

// 直到当前元素能入栈满足单调递减
descendStack.push(i);
}
return res;
}
}
```


Expand Down