每日温度
想要观测到更高的气温, 至少需要等待的天数
暴力解法:
这里暂时不做太多阐述
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int length = temperatures.length;
int[] ans = new int[length];
int[] next = new int[101];
Arrays.fill(next, Integer.MAX_VALUE);
for (int i = length - 1; i >= 0; --i) {
int warmerIndex = Integer.MAX_VALUE;
for (int t = temperatures[i] + 1; t <= 100; ++t) {
if (next[t] < warmerIndex) {
warmerIndex = next[t];
}
}
if (warmerIndex < Integer.MAX_VALUE) {
ans[i] = warmerIndex - i;
}
next[temperatures[i]] = i;
}
return ans;
}
}
单调栈:
可以维护一个存储下标的单调栈,从栈底到栈顶的下标对应的温度列表中的温度依次递减。如果一个下标在单调栈里,则表示尚未找到下一次温度更高的下标。
- 保证栈内从头到尾都是递增(从大到小)的, 以下三种情况:
- 如果遍历到的元素比栈内元素大: 那么栈内元素弹出, 更新result数组(根据题意就是栈顶右边的元素就是要找的)
- 如果遍历道德元素比栈内元素小或者等于: 那么直接加入栈
- 栈内元素存储下标
细节:
- 栈内首先要放0进去, 相当于最小值
- result数组根据栈内存储的下标, 更新数组i-stack.peek
- 第二个判断里面用while循环来操作
class Solution {
public int[] dailyTemperatures(int[] temp) {
int len = temp.length;
//初始化结果数组
int[] res = new int[len];
Deque<Integer> stack = new LinkedList<>();
//先初始化个0进去
stack.push(0);
//然后开始遍历
for(int i = 1; i < len; i++){
//别忘了栈里面是下标
if(temp[i] <= temp[stack.peek()]){
stack.push(i);
} else {
//这里用while循环判断
//细节:需要先判断不为空, 否则会空指针
while(!stack.isEmpty() && temp[i] > temp[stack.peek()]){
//更新res
res[stack.peek()] = i - stack.peek();
stack.pop();
}
//这个是为了保证栈的顺序是按照i来的
stack.push(i);
}
}
return res;
}
}
下一个更大元素
给两个不重复的数组, 其中nums1是nums2的子集, 找出nums1中的每个元素在nums2中的下一个比其大的值, 要在对应的位置后面,否则-1
- 既然是要找对因nums1的数组, 那么先初始化个长度为num1len的res数组, 默认为-1
- 题目没有重复元素, 所以可以用map, 根据数值快速找到下标
- 顺序也是栈头到栈尾是从小到大
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int[] res = new int[len1];
//初始化值为-1
Arrays.fill(res, -1);
Stack<Integer> temp = new Stack<>();
HashMap<Integer, Integer> map = new HashMap<>();
temp.push(0);
//把map里面填满nums1的值
for(int i = 0; i < len1; i++){
map.put(nums1[i], i);
}
//这里遍历nums2来判断
for(int i = 1; i < nums2.length; i++){
if(nums2[i] <= nums2[temp.peek()]){
temp.push(i);
} else {
while(!temp.isEmpty() && nums2[i] > nums2[temp.peek()]){
//判断map的元素是否在2出现过
if(map.containsKey(nums2[temp.peek()])){
//出现过, 那么用map找到对应的下标
Integer index = map.get(nums2[temp.peek()]);
res[index] = nums2[i];
}
temp.pop();
}
temp.push(i);
}
}
return res;
}
}