var dailyTemperatures = function(temperatures) { let n = temperatures.length let stack = [0] let res = Array(n).fill(0) for(let i=1;i<n;i++){ let top = stack[stack.length-1] //小于和等于的情况,直接压入栈 if (temperatures[i] === temperatures[top]){ stack.push(i) } elseif(temperatures[i] < temperatures[top]){ stack.push(i) } //当前元素大于栈顶元素的情况,要计算距离, //删掉栈顶元素知道所有小于当前元素的栈顶元素被删完,压入当前元素 else{ while (stack.length && temperatures[i] > temperatures[stack[stack.length-1]]) { top = stack.pop() res[top] = i-top } stack.push(i) } } return res };
var nextGreaterElement = function (nums1, nums2) { const m = nums1.length const n = nums2.length let stack = [nums2[0]] let res = Array(m).fill(-1) let map = newMap() for (let i = 0; i < m; i++) { map.set(nums1[i],i) } for (let j = 1; j < n; j++) { let top = stack[stack.length-1] if (nums2[j]<top || nums2===top) stack.push(nums2[j]) else{ // console.log(res) while(stack.length && nums2[j]>stack[stack.length-1]){ top = stack.pop() if (map.has(top)){ res[map.get(top)] = nums2[j]
var nextGreaterElements = function(nums) { let n = nums.length let res = Array(n).fill(-1) let stack = [0] for(let i=1;i<n*2;i++){ let j = i if (i>=n) j = i - n while (stack.length && nums[j] > nums[stack[stack.length - 1]]) { let top = stack.pop() res[top] = nums[j] } stack.push(j) } return res };
var trap = function(height) { let n = height.length let res = 0 let stack = [0] for(let i=1;i<n;i++){ while(stack.length && height[i]>height[stack[stack.length-1]]){ let top = stack.pop() if (stack.length === 0) break let topl = stack[stack.length-1] res += (Math.min(height[i],height[topl])-height[top]) * (i-topl-1) } stack.push(i) } return res };
var largestRectangleArea = function(heights) { heights = [0,...heights,0] let n = heights.length let maxArea = 0 let stack =[0] for (let i=1;i<n;i++){ while(heights[i]<heights[stack[stack.length-1]]){ let top = stack.pop() let topl = stack[stack.length-1] let w = i-topl-1 maxArea = Math.max(maxArea,w*heights[top]) } stack.push(i) } return maxArea };