Skip to content
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

【单调栈】下一个更大元素 I #399

Open
dossweet opened this issue Jan 17, 2023 · 1 comment
Open

【单调栈】下一个更大元素 I #399

dossweet opened this issue Jan 17, 2023 · 1 comment

Comments

@dossweet
Copy link
Contributor

来源:力扣第496题

题目描述:

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

解题思路:

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
let nextGreaterElement = function (nums1, nums2) {
  let stack = [];
  let map = new Map();
  for (let i = 0; i < nums2.length; i++) {
    while (stack.length && nums2[i] > nums2[stack[stack.length - 1]]) {
      let index = stack.pop();
      map.set(nums2[index], nums2[i]);
    }
    stack.push(i);
  }

  let res = [];
  for (let j = 0; j < nums1.length; j++) {
    res[j] = map.get(nums1[j]) || -1;
  }

  return res;
};
@topulikeweb
Copy link

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
var dailyTemperatures = function (temperatures) {
  let res = new Array(temperatures.length).fill(0)
  // 存放索引的单调栈
  let stack = [0]
  for (let i = 0; i < temperatures.length; i++) {
    let element = temperatures[i]
    // 和栈顶元素进行比较
    while (element > temperatures[stack[stack.length - 1]]) {
      // 弹出栈顶
      let index = stack.pop()
      res[index] = i - index
    }
    stack.push(i)
  }
  return res
};

console.log(dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants