记录微软技术面考题。
注意:正确理解题意,明白面试官要求,有时候只讲出解题思路即可,但要讲出“单调栈”核心,考察面广。
题目要求


思路
题意:遍历温度数组,找出经过几天才会比当天的温度高,求出需要经过的天数。
方法:单调栈。遍历每日温度,维护单调栈;
- 若栈为空或当日温度小于栈顶温度则直接入栈;
- 反之,若当日温度大于栈顶温度,说明栈顶元素的升温日已经找到了,则将栈顶元素出栈,计算其与当日相差的天数即可。
解题步骤
- 第一天,index0 - 23度,23入栈;
- 第二天,index1 - 24度,因为 24 > 23,所以23出栈,index1 - index0 = 1,res[0] = 1;此时,栈为空,24入栈;
- 第三天,index2 - 25度,因为 25 > 24,所以24出栈,index2 - index1 = 1,res[1] = 1;此时栈为空,所以25入栈;
- 第四天,index3 - 21度,因为 21 < 25,则21入栈;
- 第五天,index4 - 19度,因为 19 < 21,则19入栈;
- 第六天,index5 - 22度,因为 22 > 19,则栈顶元素升温日是第六天,所以19出栈,index5 - index4 = 1, 则res[4] = 1;
此时栈顶温度21,仍小于22,则栈顶元素21出栈,index5 - index3 = 2,则res[3] = 2;
此时栈顶温度25,22 < 25,所以 22 入栈; - 第7天,index6 - 26度,26 > 22,所以22出栈,index6 - index5 = 1,res[5] = 1;
此时栈顶温度为25,26 > 25,所以25出栈,index6 - index2 = 4,res[2] = 4;
此时栈顶为空,所以26入栈; - 第八天,index7 - 23度,23 < 26,所以23入栈,遍历结束,后面没有温度,所以res[6] = res[7] = 0。
注意:题目要求的是升温的天数,不是升温后的温度,因此栈中应该存储下标,而非温度。
Code part
var dailyTemperatures = function(temperatures) {
let stack = [],len = temperatures.length
let res = new Array(len).fill(0) //注意,res 默认设置0
for(let i = 0; i < len;i++){
//当前元素 > 栈顶元素
while(temperatures[i] > temperatures[stack[stack.length - 1]]){
//栈顶元素出栈
let topIndex = stack.pop()
res[topIndex] = i - topIndex
}
//当前元素入栈
stack.push(i)
}
return res
};
本文介绍了如何利用单调栈解决LeetCode中的739每日温度问题。通过遍历温度数组,当遇到更高温度时,计算与当前天数的差值,得到升温所需的天数。解题过程中详细阐述了单调栈的工作原理和操作步骤。
431

被折叠的 条评论
为什么被折叠?



